1.打开及关闭文件
打开文件通常使用open()函数打开文件。
open()函数返回的对象中,存在一个叫close()的方法。关闭文件通常使用close()。
2.写文件
模式:w(重头写),文件不存在的情况下,会自动创建文件。
try:
file = open("藏头诗.txt","w",encoding="GBK")#文件位置,模式,文件编码
except FileNotFoundError as e:
print("出现了问题:"+e.__repr__())
file.writelines("我作飞鸟云随翼\n喜风伴柳轻入梦\n欢歌笑语十指扣\n你梦若记此生中")
file.close()
运行结果如下:
3.追加内容
模式:a(追加内容)。
如果先写的内容没有完整,就需要追加内容。
try:
file = open("藏头诗.txt","w",encoding="GBK")#文件位置,模式,文件编码
except FileNotFoundError as e:
print("出现了问题:"+e.__repr__())
file.writelines("我作飞鸟云随翼\n喜风伴柳轻入梦")
try:
file = open("藏头诗.txt","a",encoding="GBK")#文件位置,模式,文件编码
except FileNotFoundError as e:
print("出现了问题:"+e.__repr__())
file.writelines("\n欢歌笑语十指扣\n你梦若记此生中")
file.close()
4.读文件
模式:r(读出)
try:
file = open("藏头诗.txt","r",encoding="GBK")#文件位置,模式,文件编码
except FileNotFoundError as e:
print("出现了问题:"+e.__repr__())
for i in file:
print(i,end="")
file.close()
运行结果如下:
5.复制文件内容
将藏头诗.txt里面的东西复制到藏头诗1.txt
file1 = open("藏头诗.txt","r",encoding="GBK")
file2 = open("藏头诗1.txt","w",encoding="GBK")
file2.writelines(file1.readlines())
write适合写入字符,字符串 writelines适合写入列表
要注意w,a,r这三种模式的用法。