python文件操作
一、打开文件方法
r:以只读方式打开
r+:可读可写
w:以只写方式打开
w+:写读
a:以追加方式打开
a+:同a
U:表示在读取时,可以将 \r \n \r\n自动转换成 \n
rU:
r+U:
b:表示读取二进制
rb:
wb:
ab:
f = open('test.txt','r') #以只读模式打开 print(f.read()) #打印文件内容 f.close() #关闭文件
二、文件操作方法
1.tell()
获取当前指针位置
f = open('test.txt','r') #以只读模式打开 print(f.tell()) #0 f.close()
2.write() 写入内容
f = open('test.txt','w') #以只写模式打开 f.write('123') #写入内容 f.close() #关闭文件
3.seek()
f.seek(5) #指定文件中指针位置 print(f.read())
4.truncate()
截断数据,只保留之前的数据
f = open('test.log','r+',encoding='utf-8') f.seek(5) f.truncate() f.close()
5.writelines() 将一个字符串列表写入文件
6.close() 关闭文件
三、with
使用with不用关闭文件,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
with open('test.txt','r') as f: print(f.read()) with open('test.txt') as f, open('test1.txt') as f1: #同时打开多个文件
read() #返回值为包含整个文件内容的一个字符串
readline() #返回值为文件下一行内容的字符串
readlines() #返回值为整个文件内容的列表,每项是以换行符为结尾的一行字符串
with open("pai.txt") as file: lines = file.read() print(lines.rstrip()) 3.1415926535 8979323846 2643383279 5028841971 69399375105
with open("pai.txt") as file: lines = file.readline() print(lines.rstrip()) 3.1415926535
with open("pai.txt") as file: lines = file.readlines() print(lines) ['3.1415926535\n', ' 8979323846\n', ' 2643383279\n', ' 5028841971\n', ' 69399375105'] with open("pai.txt") as file: for line in file.readlines(): print(line.rstrip()) 3.1415926535 8979323846 2643383279 5028841971 69399375105优质内容筛选与推荐>>