替换文件内容中的字符串

时间:2010-11-08 21:16:35

标签: python string file-io

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

8 个答案:

答案 0 :(得分:155)

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

答案 1 :(得分:69)

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

我在这个例子中使用the with statement,它在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:
        s = f.read()
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

值得一提的是,如果文件名不同,我们可以使用单个with语句更优雅地完成此操作。

答案 2 :(得分:26)

  #!/usr/bin/python

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

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

答案 3 :(得分:10)

这样的东西
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')

<do stuff with the result>

答案 4 :(得分:6)

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)

答案 5 :(得分:5)

如果您使用的是Linux,只想将dog替换为cat,则可以执行以下操作:

<强>的text.txt:

Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!

Linux命令:

sed -i 's/dog/cat/g' test.txt

<强>输出:

Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!

原帖:https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands

答案 6 :(得分:4)

使用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_textwrite_text使用两个不同的变量。

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

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

答案 7 :(得分: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)