Example input
[specific Python environments or purposes]: 'e.g., automation scripts, data analysis scripts, web scraping scripts'
[specific task or feature]: 'e.g., file manipulation, API consumption, text processing'
Example output
Certainly! Here's a collection of Python code snippets optimized for automation scripts, focusing on file manipulation tasks. Each snippet includes error handling and clear documentation for ease of use and integration. These snippets cover various common file manipulation tasks encountered in automation scripts:
1. **Read File Contents:**
```python
def read_file(file_path):
"""
Read contents from a file.
Args:
file_path (str): Path to the file.
Returns:
str: Contents of the file.
"""
try:
with open(file_path, 'r') as file:
contents = file.read()
return contents
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return None
except Exception as e:
print(f"Error: {e}")
return None
```
2. **Write to File:**
```python
def write_to_file(file_path, content):
"""
Write content to a file.
Args:
file_path (str): Path to the file.
content (str): Content to be written.
Returns:
bool: True if write successful, False otherwise.
"""
try:
with open(file_path, 'w') as file:
file.write(content)
return True
except Exception as e:
print(f"Error: {e}")
return False
```
3. **Append to File:**
```python
def append_to_file(file_path, content):
"""
Append content to a file.
Args:
file_path (str): Path to the file.
content (str): Content to be appended.
Returns:
bool: True if append successful, False otherwise.
"""
try:
with open(file_path, 'a') as file:
file.write(content)
return True
except Exception as e:
print(f"Error: {e}")
return False
```
4. **Copy File:**
```python
import shutil
def copy_file(source_path, destination_path):
"""
Copy a file from source to destination.
Args:
source_path (str): Path to the source file.
destination_path (str): Path to the destination file.
Returns:
bool: True if copy successful, False otherwise.
"""
try:
shutil.copy2(source_path, destination_path)
return True
except FileNotFoundError:
print(f"Error: File '{source_path}' not found.")
return False
except Exception as e:
print(f"Error: {e}")
return False
```
5. **Delete File:**
```python
def delete_file(file_path):
"""
Delete a file.
Args:
file_path (str): Path to the file.
Returns:
bool: True if deletion successful, False otherwise.
"""
try:
os.remove(file_path)
return True
except FileNotFoundError:
print(f"Error: File '{file_path}' not found.")
return False
except Exception as e:
print(f"Error: {e}")
return False
```
These snippets cover basic file manipulation tasks, but there are numerous other functionalities you can implement, such as directory manipulation, file compression, and more. Feel free to explore and expand upon these snippets as needed!