文件读取
文件读取可分为以下步骤:
打开文件
读取文件内容
关闭文件
文件打开模式:
读取文件常用函数:
示例代码:
f = open('./file.txt',mode='r',encoding='utf-8')
content = f.read(10) # 读取前十个字符
print(content)
f.close()f = open('./file.txt',mode='r',encoding='utf-8')
content = f.readline(5) # 读取第一行的前 5 个字符
print(content)
f.close()f = open('./file.txt',mode='r',encoding='utf-8')
content = f.readlines() #返回一个列表:['hello,python\n', 'hello,nihao\n', 'hello,cj\n']
print(content)
f.close()with 读取文件,自动关闭close():
with open('./file.txt',mode='r',encoding='utf-8') as f: print(f.readlines())循环读取,防止文件太大出现错误:
with open('./file.txt',mode='r',encoding='utf-8') as f: # print(f.readlines())
文件写入
with open('./file.txt', mode='w',encoding='utf-8') as f:
f.write('ni hao2')