使用Python进行文件操作:读写、重命名问题案例

原创 雨点打透心脏的1/2处 2025-01-26 21:33 49阅读 0赞

在Python中,我们可以使用内置的open()函数来进行文件的操作。以下是一些常见的文件操作以及例子:

  1. 读取文件
    ```python
    file = open(‘example.txt’, ‘r’)
    content = file.read()
    file.close() # 关闭文件以节省资源

print(content) # 输出文件内容

  1. 2. **写入文件**:
  2. ```python
  3. file = open('new_example.txt', 'w')
  4. file.write('Hello, World! \n') # 写入多行内容
  5. file.close()
  6. # 检查是否正确创建了新文件
  7. if os.path.exists('new_example.txt'):
  8. print("File created successfully!")
  9. else:
  10. print("Failed to create new file!")
  1. 重命名文件
    ```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))))
```

请注意,上述代码可能需要根据你的具体需求和文件路径进行适当的调整。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,49人围观)

还没有评论,来说两句吧...

相关阅读