Python读写txt文本文件的操作方法全解析

一、文件写入(慎重,小心别清空原本的文件)
步骤:打开 -- 写入 -- (保存)关闭
直接的写入数据是不行的,因为默认打开的是'r' 只读模式

使用r+ 模式不会先清空,但是会替换掉原先的文件,如下面的例子:hello boy! 被替换成hello aay!

path='G:\Python学习/test1.txt'
f=open(path,'r+')
f.write('hello aa!')
f.close()

如何实现不替换?

可以看到,如果在写之前先读取一下文件,再进行写入,则写入的数据会添加到文件末尾而不会替换掉原先的文件。这是因为指针引起的,r+ 模式的指针默认是在文件的开头,如果直接写入,则会覆盖源文件,通过read() 读取文件后,指针会移到文件的末尾,再写入数据就不会有问题了。这里也可以使用a 模式

2016626170852899.png (713×317)

文件对象的方法:
f.readline()   逐行读取数据

f.next()   逐行读取数据,和f.readline() 相似,唯一不同的是,f.readline() 读取到最后如果没有数据会返回空,而f.next() 没读取到数据则会报错.而 Python3中这个方法已经不再使用,因此会报错。

f.writelines()   多行写入

f.seek(偏移量,选项)
(1)选项=0,表示将文件指针指向从文件头部到“偏移量”字节处
(2)选项=1,表示将文件指针指向从文件的当前位置,向后移动“偏移量”字节
(3)选项=2,表示将文件指针指向从文件的尾部,向前移动“偏移量”字节

偏移量:正数表示向右偏移,负数表示向左偏移

f.flush()    将修改写入到文件中(无需关闭文件)

f.tell()   获取指针位置

四、内容查找和替换
1、内容查找

实例:统计文件中hello个数
思路:打开文件,遍历文件内容,通过正则表达式匹配关键字,统计匹配个数。

import re
f =open('G:\Python学习/test1.txt')
source = f.read()
f.close()
print(re.findall(r'hello',source))
s = len(re.findall(r'hello',source))
print(s)

#法二:
fp=open('G:\Python学习/test1.txt','r')
count=0

for s in fp.readlines():
    li=re.findall('hello',s)
    if len(li)>0:
        count=count+len(li)
print('you %d 个hello'%count)

2、替换
实例:把test1.txt 中的hello全部换为"hi",并把结果保存到hello.txt中。

f1=open('G:\Python学习/test1.txt')
f2=open('G:\Python学习/hello.txt','r+')
for s in f1.readlines():
    f2.write(s.replace('hello','hi'))
f1.close()
f2.close()
f2=open('G:\Python学习/hello.txt','r')
f2.readlines()

实例:读取文件test.txt内容,去除空行和注释行后,以行为单位进行排序,并将结果输出为result.txt。test.txt 的内容如下所示:

#some words
 
Sometimes in life,
You find a special friend;
Someone who changes your life just by being part of it.
Someone who makes you laugh until you can't stop;
Someone who makes you believe that there really is good in the world.
Someone who convinces you that there really is an unlocked door just waiting for you to open it.
This is Forever Friendship.
when you're down,
and the world seems dark and empty,
Your forever friend lifts you up in spirits and makes that dark and empty world
suddenly seem bright and full.
Your forever friend gets you through the hard times,the sad times,and the confused times.
If you turn and walk away,
Your forever friend follows,
If you lose you way,
Your forever friend guides you and cheers you on.
Your forever friend holds your hand and tells you that everything is going to be okay. 
f=open('G:\Python学习/test.txt','r')
result=list()
for line in f.readlines():#逐行读取数据
    line=line.strip()#去掉每行头尾空白
    if not len(line) or line.startswith('#'):#判断是否是空行或注释行
        continue
result.append(line)#保存        
result.sort()#排序结果
print(result)
f1=open('G:\Python学习/result.txt','w')
f1.write('%s'%'\n'.join(result))

结果如下:

f1=open('G:\Python学习/result.txt','r')
f1.read()

猜你喜欢

转载自blog.csdn.net/Winnycatty/article/details/84063920