您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在Python中覆盖文件中的字符

在Python中覆盖文件中的字符

使用fileinputinplace=True修改文件内容

import fileinput
import sys
for line in fileinput.input("test.txt",inplace=True):
    # replaces all occurrences of apples in each line with oranges
    sys.stdout.write(line.replace("apples","oranges"))

输入:

Marry has 10 carrots
Bob has 15 apples
Tom has 4 bananas

输出

Marry has 10 carrots
Bob has 15 oranges
Tom has 4 bananas

使用re避免匹配子字符串:

import fileinput
import sys
import re
# use word boundaries so we only match "apples"  
r = re.compile(r"\bapples\b")
for line in fileinput.input("test.txt",inplace=True):
    # will write the line as is or replace apples with oranges and write
    sys.stdout.write(r.sub("oranges",line))

删除所有遗留词:

import fileinput
import sys
for line in fileinput.input("test.txt",inplace=True):
    # split on the last whitespace and write everything up to that
    sys.stdout.write("{}\n".format(line.rsplit(None, 1)[0]))

输出

Marry has 10
Bob has 15
Tom has 4

您还可以使用tempfile.NamedTemporaryFile使用以上任何逻辑将更新后的行写入,然后使用shutil.move替换原始文件

from tempfile import NamedTemporaryFile
from shutil import move

with open("test.txt") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    for line in f:
        temp.write("{}\n".format(line.rsplit(None, 1)[0]))

# replace original file with updated content
move(temp.name,"test.txt")

您需要通过dir="."delete=False因此当我们退出with时,文件文件不会被删除,我们可以使用.name属性访问该文件以传递给shutil。

python 2022/1/1 18:42:35 有305人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶