使用Python进行文件操作:读写、重命名问题案例
在Python中,我们可以使用内置的open()
函数来进行文件的操作。以下是一些常见的文件操作以及例子:
- 读取文件:
```python
file = open(‘example.txt’, ‘r’)
content = file.read()
file.close() # 关闭文件以节省资源
print(content) # 输出文件内容
2. **写入文件**:
```python
file = open('new_example.txt', 'w')
file.write('Hello, World! \n') # 写入多行内容
file.close()
# 检查是否正确创建了新文件
if os.path.exists('new_example.txt'):
print("File created successfully!")
else:
print("Failed to create new file!")
- 重命名文件:
```python
import os
选择需要操作的文件路径
file_path = ‘example.txt’
获取当前目录
dir_path = os.path.dirname(file_path)
新的名字
new_name = ‘renamed_example.txt’
使用os模块的rename函数进行重命名
if os.path.exists(new_name)):
print(f”Error: ‘{new_name}’ already exists.”)
else:
os.rename(file_path, os.path.join(dir_path, new_name))))
```
请注意,上述代码可能需要根据你的具体需求和文件路径进行适当的调整。
还没有评论,来说两句吧...