python的文件读写操作

 

BEGIN:

1、读文件

file = 'E:\\text.txt' 
f = open(file) #打开文件
result = f.read() #读文件
f.close() #关闭文件
print(result) #打印文件内容  

或(r, 只读模式)

file = 'E:\\text.txt' #文件路径
f = open(file,mode='r',encoding='utf-8') #只读方式打开文件
result = f.read() #读文件
f.close() #关闭文件
print(result) #打印文件内容  

2、写文件

1)w,只写模式(文件不可读,若文件不存在则创建,若存在则清空内容再写入)

data = "HelloWorld" #写入的内容
file = 'E:\\text.txt' #文件路径
f = open(file,mode='w',encoding='utf-8') #只写方式打开文件
f.write(data) #将内容写入
f.close() #关闭文件

2)a,只追加写模式(不可读,若文件不存在则创建,若存在则内容追加在原文件内容后面)

data = '\n Welcome to Python! \n' #追加的内容
file = 'E:\\text.txt' #文件路径
f = open(file,mode='a',encoding='utf-8') #只追加写方式打开文件
f.write(data) #将内容写入
f.close() #关闭文件

3、读写文件

  r+,读写模式,先读后写,若先写再读则读取内容为空

data = '\n I love python ! \n' #追加的内容
file = 'E:\\text.txt' #文件路径
f = open(file,mode='r+',encoding='utf-8') #读写模式打开文件
print(f.read()) #读文件,此时读取的内容是未重写时原文件内容
f.write(data) #将内容写入
f.close() #关闭文件

4、写读模式

1)w+,先清空原文件内容再写入新内容,再读取

data = ' 学习python \n' #写入的内容
file = 'E:\\text.txt' #文件路径
f = open(file,mode='w+',encoding='utf-8') #写读模式打开文件
f.write(data) #将内容写入
f.seek(0) #将光标移到文件头
print(f.read()) #读文件,此时读取的内容是重写后的文件内容
f.close() #关闭文件

 

2)a+,不清空内容,后面追加写入,再读

data = ' 学习python \n' #写入的内容
file = 'E:\\text.txt' #文件路径
f = open(file,mode='a+',encoding='utf-8') #写读模式打开文件,不覆盖原内容
f.write(data) #将内容写入
f.seek(0) #将光标移到文件头(位置0)
print(f.read()) #读文件,此时读取的内容是追加后的文件内容
f.close() #关闭文件

 

END.

posted @ 2020-04-02 16:06  Gangpei  阅读(333)  评论(0)    收藏  举报