文件的读写操作
文件对象 = open(文件路径,文件打开方式,encoding = 文本编码方式)
操作文件对象
文件对象.close()
with open(文件路径,文件打开方式,encoding = 文本编码方式) as 文件对象:
操作文件对象
方法一:
f = open(r'.\file\text.txt',encoding = 'utf-8')
print(f.read())
f.close()
print(f.read()) # ValueError: I/O operation on closed file.
方法二:
with open(r'.\file\text.txt',encoding = 'utf-8') as f :
print(f.read())
print(f.read()) # ValueError: I/O operation on closed file.
1)文件对象.read() - 从文件读写位置开始,读到文件结尾
with open(r'.\file\text.txt',encoding = 'utf-8') as f :
content = f.read()
print('1',content)
content = f.read()
print('2',content)
#1
#abc
#床前明月光,疑似地上霜
#举杯邀明月,对影成三人
#2
2) 文件对象.readline() - 只针对文本文件有效,读文本文件的一行内容
with open(r'.\file\text.txt',encoding = 'utf-8') as f :
content = f.readline()
print(content)
content = f.readline()
print(content)
练习:一行一行读文件,读完为止
def read1(file):
with open(file,'r',encoding = 'utf-8') as f:
while True:
a = f.readline()
if not a:
break
print(a)
read1(r'.\file\text.txt')
3) 文件对象.readlines()- 一行一行读,读完为止,返回的是一个列表,列表中的元素是每一行的内容
文件对象.write(内容)-
with open(r'.\file\text.txt','a',encoding = 'utf-8') as f :
f.write('\n两岸猿声啼不住,柳暗花明又一村')