zl程序教程

您现在的位置是:首页 >  Python

当前栏目

python读写txt 文件

2023-04-18 14:16:24 时间

在这里插入图片描述

一、读文件

步骤:打开 – 读取 – 关闭
f= open(‘D:pythontxt1.txt’)
f.read() #返回txt 文件的所有内容
在这里插入图片描述

while True:
lines = f.readline() # 按行读取数据,行自动+1
if not lines:
break
pass
print(lines)
在这里插入图片描述
二、文件写入
f1= open(‘D:pythontxt1.txt’,‘w’)
f1.write(‘5.5 5.6!’)
f1.close() //只有close的时候文件才会被保存
f2= open(‘D:pythontxt1.txt’,‘r’)
print(’*********************’)
print(f2.read())
在这里插入图片描述
直接写入会覆盖之前的文件,以下方法可以追加写入末尾
f1= open(‘D:pythontxt1.txt’,‘a’)
f1.write(’ hello world3’)
f1.close()

f1= open(‘D:pythontxt1.txt’,‘r+’)
f1.read()
f1.write(’ hello world3’)
f1.close()
如果在写之前先读取一下文件,再进行写入,则写入的数据会添加到文件末尾而不会替换掉原先的文件。这是因为指针引起的,r+ 模式的指针默认是在文件的开头,如果直接写入,则会覆盖源文件原来位置的等长字符,通过read() 读取文件后,指针会移到文件的末尾,追加到源文件末尾

在这里插入图片描述