Description
Inputs:
[specific Python libraries or modules]: 'e.g., os, shutil, requests'
[specific automation task]: 'e.g., file manipulation, web scraping, API interaction'
Output:
Certainly! Here's a set of Python snippets using the `os` and `shutil` modules for file manipulation tasks. Each snippet is accompanied by explanations and error handling to ensure robustness. Feel free to use, modify, and provide feedback!
### Snippet 1: Copying Files
```python
import shutil
def copy_file(src, dest):
"""
Copy a file from source to destination.
Args:
src (str): Path to the source file.
dest (str): Path to the destination directory.
Returns:
bool: True if successful, False otherwise.
"""
try:
shutil.copy(src, dest)
return True
except FileNotFoundError:
print("Source file not found.")
return False
except PermissionError:
print("Permission denied.")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
# Usage example:
# copy_file('source_file.txt', 'destination_directory')
```
### Snippet 2: Moving Files
```python
import shutil
def move_file(src, dest):
"""
Move a file from source to destination.
Args:
src (str): Path to the source file.
dest (str): Path to the destination directory.
Returns:
bool: True if successful, False otherwise.
"""
try:
shutil.move(src, dest)
return True
except FileNotFoundError:
print("Source file not found.")
return False
except PermissionError:
print("Permission denied.")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
# Usage example:
# move_file('source_file.txt', 'destination_directory')
```
### Snippet 3: Deleting Files
```python
import os
def delete_file(file_path):
"""
Delete a file.
Args:
file_path (str): Path to the file to be deleted.
Returns:
bool: True if successful, False otherwise.
"""
try:
os.remove(file_path)
return True
except FileNotFoundError:
print("File not found.")
return False
except PermissionError:
print("Permission denied.")
return False
except Exception as e:
print(f"An error occurred: {e}")
return False
# Usage example:
# delete_file('file_to_delete.txt')
```
These snippets cover common file manipulation tasks with error handling for FileNotFoundError and PermissionError. Users can utilize these functions in their scripts and provide feedback for improvements or suggest new automation challenges for future snippet development.
Reviews
There are no reviews yet.