0
点赞
收藏
分享

微信扫一扫

python txt文本操作


1. 读写模式

模式

要求

r

读取文件,若文件不存在则会报错

w

写入文件,若文件不存在则会先创建再写入,会覆盖原文件

a

写入文件,若文件不存在则会先创建再写入,但不会覆盖原文件,而是追加在文件末尾

rb,wb

分别于r,w类似,但是用于读写二进制文件

r+

可读、可写,文件不存在也会报错,写操作时会覆盖

w+

可读,可写,文件不存在先创建,会覆盖

a+

可读、可写,文件不存在先创建,不会覆盖,追加在末尾

2. 读取所有内容返回字符串

with open('test.txt', 'r') as f:
data = f.read()
print(data)

3.仅读取一行

with open('test.txt', 'r') as f:
line = f.readline()
while True:
if not line:
break
line = line[:-1] if '\n' in line else line

print(line)
line = f.readline()

4. 原样输出

with open('test.txt', 'r') as f:
for line in f.readlines():
line = line.strip('\n') #删除每一行最后面的换行符
print(line)

5. 写入

with open('test.txt', 'w') as f:
f.write('你好6!')


举报

相关推荐

0 条评论