返回顶部

python之文件修改两种方式

python之文件修改两种方式

Python修改文件两种方式: 一是文本编辑方式,如notepate ;二是:文件写入

方式一

方式一缺点:大文件会浪费内存,不浪费硬盘空间
# cat a.txt   搜素18替换20
wei  22  man
wang  18  female
zhang  18  female

# cat r7.py
#!/bin/python3
# -*- coding: utf-8 -*-
with open('a.txt',mode='rt',encoding='utf-8') as f:
    l=f.read()                    #文件较大,占用内存较大
    l1=l.replace('18','20')
    print(l1)
with open('a.txt',mode='wt',encoding='utf-8') as f1:
    f1.write(l1)

# python3 r7.py
wei  22  man
wang  20  female
zhang  20  female

# cat a.txt
wei  22  man
wang  20  female
zhang  20  female

方式二

方式二缺点是:浪费硬盘空间,不浪费内存空间

# cat a.txt
wei  22  man
wang  20  female
zhang  20  female

# cat r8.py
#!/bin/python3
# -*- coding: utf-8 -*-
import os
with open('a.txt',mode='rt',encoding='utf-8') as f,\
    open('.a.txt.swap',mode='wt',encoding='utf-8') as f1:
    for i in f:
        f1.write(i.replace('20','18'))

os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')

# cat a.txt
wei  22  man
wang  18  female
zhang  18  female

Shell方式

shell 实现方式有很多:sed ,tr + > ,cat + > 等等

# cat a.txt
wei  22  man
wang  18  female
zhang  18  female

#一步实现文件修改替换
# sed -i.bak 's/18/20/' a.txt

# cat a.txt
wei  22  man
wang  20  female
zhang  20  female

 

posted @ 2022-05-03 21:47  九尾cat  阅读(928)  评论(0编辑  收藏  举报