替换文件内容中的字符串


97

如何打开文件Stud.txt,然后用“橙色”替换出现的“ A”?


4
请(一如既往)遵循一般性的问题准则,说明任何特殊限制,显示到目前为止您已经尝试过的内容,并询问具体使您感到困惑的地方。

18
也请用[homework]标签标记您的作业。
S.Lott 2010年

Answers:


181
with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))

8
文本模式下的“ t”仅适用于Python 3。另外,您为输出文件提供了上下文管理器,但是无法关闭输入文件,这似乎是不一致的。
史蒂文·鲁姆巴尔斯基

1
@katrielalex:没有投票,我只是没有投票。但是,给出家庭作业答案并不是正确的方法
BlueRaja-Danny Pflughoeft 2010年

嗯,没有注意到这被标记为“作业”。我不会删除答案,但以后会更加小心
Gareth Davidson 2010年

21
“给出家庭作业问题的答案”是一个极其愚蠢的评论。如果有人需要帮助,请帮助他们。并非每个人都在寻求自己的硬件,有些人实际上想学习一些东西……
KingMak 2014年

5
我确实需要做这项作业,它极大地帮助了我
mikeybeck

78

如果要替换同一文件中的字符串,则可能必须将其内容读入局部变量,将其关闭,然后重新打开以进行写入:

在此示例中,我使用with语句,该语句with块终止后关闭文件-通常在最后一条命令完成执行时执行,或在例外情况下执行。

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

值得一提的是,如果文件名不同,我们可以用一条with语句来做得更好。


此解决方案更好,因为您不像上面的答案那样重命名文件。

47
#!/usr/bin/python

with open(FileName) as f:
    newText=f.read().replace('A', 'Orange')

with open(FileName, "w") as f:
    f.write(newText)

1
简明扼要的最佳答案IMO
Briford Wylie

11

就像是

file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

OP提到了“任何出现”的含义,即使它是子字符串-也不适合您的示例。
Durdu

7
with open('Stud.txt','r') as f:
    newlines = []
    for line in f.readlines():
        newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
    for line in newlines:
        f.write(line)


2

使用pathlib(https://docs.python.org/3/library/pathlib.html

from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))

如果输入文件和输出文件不同,则将对read_text和使用两个不同的变量write_text

如果您希望更改比单个替换更复杂,则可以将结果分配read_text给一个变量,对其进行处理,然后将新内容保存到另一个变量,然后使用保存新内容write_text

如果您的文件很大,则最好不要读取内存中的整个文件,而应像Gareth Davidson在另一个答案中显示的那样逐行处理(https://stackoverflow.com/a/4128192/3981273) ,当然需要使用两个不同的文件进行输入和输出。


write_text对我不起作用。它不会更新文件
Anurag

0

最简单的方法是使用正则表达式进行此操作,假设您要遍历文件中的每一行(存储“ A”的位置),则可以...

import re

input = file('C:\full_path\Stud.txt), 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file.  So we have to save the file first.

saved_input
for eachLine in input:
    saved_input.append(eachLine)

#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
    search = re.sub('A', 'Orange', saved_input[i])
    if search is not None:
        saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt), 'w')
for each in saved_input:
    input.write(each)
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.