Python 提供了丰富的文件处理功能,包括文件的读取、写入和追加等操作。
原文地址可以访问我的博客:python之文件操作
1. 打开文件:
要打开文件,可以使用 open 函数。语法如下:
# 打开文件以进行读取(默认模式)
file = open("example.txt", "r")
# 打开文件以进行写入
file = open("example.txt", "w")
# 打开文件以进行追加
file = open("example.txt", "a")
# 读取整个文件内容
content = file.read()
print(content)
# 逐行读取文件
file = open("example.txt", "r")
for line in file:
print(line.strip()) # 去除行尾的换行符
# 写入内容到文件
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("How are you?")
file.close()
# 追加内容到文件
file = open("example.txt", "a")
file.write("\nAppending new content.")
file.close()
with
?语句自动关闭文件:# 使用 with 语句自动关闭文件
with open("example.txt", "r") as file:
content = file.read()
print(content)
# 文件自动关闭,无需显式调用 close 方法
import os
if os.path.exists("example.txt"):
print("文件存在")
else:
print("文件不存在")
import shutil
shutil.copy("source.txt", "destination.txt")
import os
os.remove("example.txt")
这是一个简单的关于 Python 文件操作的教程,希望对你有帮助.转载请表明出处http://blog.tsaqhm.cn/