renaming & deleting files in Python
renaming & deleting files in Python
In Python, you can rename and delete files using the `os` module, which provides a way to interact with the operating system. Here's how you can rename and delete files:
### 1. Renaming Files:
To rename a file, you can use the `os.rename()` function. It takes two arguments: the current filename and the new filename.
```python
import os
current_filename = 'old_file.txt'
new_filename = 'new_file.txt'
os.rename(current_filename, new_filename)
```
In this example, `old_file.txt` is renamed to `new_file.txt`.
### 2. Deleting Files:
To delete a file, you can use the `os.remove()` function. It takes the filename as an argument and deletes the file.
```python
import os
filename = 'file_to_delete.txt'
os.remove(filename)
```
In this example, `file_to_delete.txt` is deleted from the filesystem.
### 3. Handling Exceptions:
Both `os.rename()` and `os.remove()` functions can raise exceptions if the specified file does not exist or if there are permission issues. It's a good practice to handle these exceptions to avoid program crashes.
```python
import os
filename = 'file_to_delete.txt'
try:
os.remove(filename)
except FileNotFoundError:
print(f"Error: {filename} not found.")
except PermissionError:
print(f"Error: Permission denied to delete {filename}.")
except Exception as e:
print(f"An error occurred: {e}")
else:
print(f"{filename} successfully deleted.")
```
In this example, the code attempts to delete the file specified in `filename`. If the file is not found or if there are permission issues, it catches the appropriate exceptions and prints an error message.
Always be cautious when deleting files, as deleted files cannot be easily recovered. Ensure that you have appropriate backups or confirmations before deleting important files in your programs.
Comments
Post a Comment