python学习笔记day09 --昨日内容回顾

作日内容回顾---文件操作

1.打开文件:打开方式,r w a ,   r+ w+ a+;   b

2.文件操作:

            读:  read() 一次性读所有,返回str字符串类型----缺点,文件太大,会造成内存爆满;

                      readlines()---一次性读所有,返回列表,每一行作为list的一个元素;

                      readline()----一行一行读;就是不知道什么时候结束?另外当文件是视频等无法一行一行读的;

                      for line in file~------- 最好的方法!!!

            写:   write():

            文件指针: seek():移动光标位置,以字节为单位;

                                tell():    告诉指针的位置;  


3.文件关闭:close()

4.文件修改:文件是不能修改的

            文件删除:      os.remove(filename)

            文件重命名:os.rename(filename,filename_new)

但是如果我们想完成“类似”文件修改的功能,可以这样操作:

读取a文件的内容,然后修改 存到另一个文件中,然后把原来文件删掉,把新文件命名为原来的文件名,这样就完成了类似文件修改的功能;

原来写的:

with open("info",mode='r',encoding='utf-8') as  file:
    for line in file:
        content=line.replace('xuanxuan','xuan')
del file
with open('info',mode='w',encoding='utf-8') as file2:
    file2.write(content)

版本二(推荐)

with open("info",mode='r',encoding='utf-8') as file1,open('info.bak',mode='w',encoding='utf-8') as file2:
    for line in file1:
        if 'xuanxuan' in line:
            line=line.replace("xuanxuan",'璇璇') #对str的任何操作都是产生新的字符串,将其赋值给变量line;
        file2.write(line)  #这个时候会产生一个新的文件 info.bak
import os
os.remove('info')  #将文件删除;
os.rename('info.bak','info') #将文件重命名;

                           

talk is cheap,show me the code
原文地址:https://www.cnblogs.com/xuanxuanlove/p/9535425.html