在日常开发中,我们经常会遇到需要对文件进行操作的场景,如读写文件、文件夹操作等。本文将为大家介绍一些 Python 中处理文件的实用技巧,让你的工作更高效。
一、读写文件
在 Python 中,我们可以使用 open()
函数打开文件,with
语句可以自动关闭文件。
- 读取文件内容:
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
- 写入文件:
with open('example.txt', 'w', encoding='utf-8') as f:
f.write('Hello, Python!')
二、遍历文件夹
使用 os
模块,我们可以轻松地遍历文件夹内的文件。
import os
folder_path = './example_folder'
for root, dirs, files in os.walk(folder_path):
for file in files:
print(os.path.join(root, file))
三、创建与删除文件夹
利用 os
模块,我们可以方便地创建和删除文件夹。
- 创建文件夹:
import os
folder_name = 'new_folder'
if not os.path.exists(folder_name):
os.makedirs(folder_name)
- 删除文件夹:
import shutil
folder_name = 'new_folder'
if os.path.exists(folder_name):
shutil.rmtree(folder_name)
四、文件路径操作
os.path
模块提供了很多文件路径操作的实用函数。
- 拼接路径:
import os
path1 = 'folder'
path2 = 'file.txt'
full_path = os.path.join(path1, path2)
print(full_path)
- 分割文件名和扩展名:
import os
filename = 'example.txt'
name, ext = os.path.splitext(filename)
print(name, ext)
五、总结
本文介绍了 Python 中处理文件的一些实用技巧,包括文件读写、遍历文件夹、创建与删除文件夹以及文件路径操作。掌握这些技巧,可以让你在处理文件时更加得心应手。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。