问题:替换文件内容中的字符串

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

How can I open a file, Stud.txt, and then replace any occurences of “A” with “Orange”?


回答 0

with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))
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

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

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

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语句来做得更好。

If you’d like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:

I am using the with statement in this example, which closes the file after the with block is terminated – either normally when the last command finishes executing, or by an exception.

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)

It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.


回答 2

#!/usr/bin/python

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

with open(FileName, "w") as f:
    f.write(newText)
#!/usr/bin/python

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

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

回答 3

就像是

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

<do stuff with the result>

Something like

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

<do stuff with the result>

回答 4

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)
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

如果您使用的是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

If you are on linux and just want to replace the word dog with catyou can do:

text.txt:

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

Linux Command:

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

Output:

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

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


回答 6

使用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) ,当然需要使用两个不同的文件进行输入和输出。

Using 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'))

If input and output files were different you would use two different variables for read_text and write_text.

If you wanted a change more complex than a single replacement, you would assign the result of read_text to a variable, process it and save the new content to another variable, and then save the new content with write_text.

If your file was large you would prefer an approach that does not read the whole file in memory, but rather process it line by line as show by Gareth Davidson in another answer (https://stackoverflow.com/a/4128192/3981273), which of course requires to use two distinct files for input and output.


回答 7

最简单的方法是使用正则表达式进行此操作,假设您要遍历文件中的每一行(存储“ 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)

easiest way is to do it with regular expressions, assuming that you want to iterate over each line in the file (where ‘A’ would be stored) you do…

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)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。