打开文件r
# 打开文件
file = open(r"E:\helloworld.txt", "r")
# 读取文件(如果不存在,报错)
txt = file.read()
# 打印文件
print(txt)
# 关闭文件
file.close()
写文件w
# 写入文件(不存在创建文件,存在则覆盖文件)
file = open(r"E:\a.txt", "w")
# 追加内容
file.write("hello python")
# 关闭文件
file.close()
追加写文件a
# 写入文件(不存在创建文件,存在在文件后面追加内容)
file = open(r"E:\b.txt", "a")
# 追加内容
file.write("hello python\n")
# 关闭文件
file.close()
打开文件指定字符集(读取中文)
# 打开文件
file = open(r"E:\简历.txt", "r", encoding="utf8")
# 读取文件(如果不存在,报错)
txt = file.read()
# 打印文件
print(txt)
# 关闭文件
file.close()
改文件内容
file = open(r"E:\b.txt", "r")
txt = file.read()
a = txt.replace("python", "world")
file.close()
fi