在Python中覆盖文件中的字符

Sin*_*ity 0 python

我想在我拥有的文件中更改一些文本,但是我找不到用python从文件中删除字符的正确方法.可能吗?例如,我有一个看起来很像这样的文件:

Marry has 10 carrots
Bob has 15 apples
Tom has 4 bananas
Run Code Online (Sandbox Code Playgroud)

现在我想改变文件中的数字,甚至是水果.我只能阅读数字,但我无法删除它们或覆盖它们.

Pad*_*ham 7

使用fileinput with inplace=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"))
Run Code Online (Sandbox Code Playgroud)

输入:

Marry has 10 carrots
Bob has 15 apples
Tom has 4 bananas
Run Code Online (Sandbox Code Playgroud)

输出:

Marry has 10 carrots
Bob has 15 oranges
Tom has 4 bananas
Run Code Online (Sandbox Code Playgroud)

使用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))
Run Code Online (Sandbox Code Playgroud)

删除所有最后的单词:

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]))
Run Code Online (Sandbox Code Playgroud)

输出:

Marry has 10
Bob has 15
Tom has 4
Run Code Online (Sandbox Code Playgroud)

您还可以使用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")
Run Code Online (Sandbox Code Playgroud)

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