1.文件操作
- 读取文件内容并输出
with open('file.txt', 'r') as f:
content = f.read()
print(content)
- 逐行读取文件内容并输出
with open('file.txt', 'r') as f:
for line in f:
print(line.strip())
- 写入文件内容
with open('file.txt', 'w') as f:
f.write('Hello, world!')
- 追加文件内容
with open('file.txt', 'a') as f:
f.write('Hello, Python!')
- 复制文件
with open('source_file.txt', 'rb') as f1, open('target_file.txt', 'wb') as f2:
f2.write(f1.read())
- 删除文件
import os
os.remove('file.txt')
- 检查文件是否存在
import os
if os.path.exists('file.txt'):
print('File exists.')
else:
print('File not found.')
- 创建文件夹
import os
os.mkdir('new_folder')
- 删除文件夹
import os
os.rmdir('new_folder')
2.清空文件
在 Python 中清空某个文件有多种方法,可以根据不同的需求选择不同的方法。
- 使用 open 函数打开文件,指定 mode 为 “w”,表示以写入模式打开文件,并清空其中的内容:
with open("file.txt", "w"):
pass
- 使用 truncate 方法将文件截断为指定大小,如果未指定大小,则默认截断到当前位置:
with open("file.txt", "r+") as f:
f.truncate(0) # 清空文件内容
- 使用 os 模块的 truncate 方法将文件截断为指定大小,如果未指定大小,则默认截断到当前位置:
import os
with open("file.txt", "r+") as f:
os.ftruncate(f.fileno(), 0) # 清空文件内容
需要注意的是,以上方法都是清空文件内容,而不是删除文件本身。
如果需要删除文件,可以使用 os 模块的 remove 方法:
import os
os.remove("file.txt") # 删除文件