简体   繁体   English

替换文件内容中的字符串

[英]Replace string within file contents

如何打开文件 Stud.txt,然后将出现的任何“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'))

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.我在这个例子中使用了 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)

It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.值得一提的是,如果文件名不同,我们可以用一条with语句更优雅地完成这项工作。

#!/usr/bin/python with open(FileName) as f: newText=f.read().replace('A', 'Orange') with open(FileName, "w") as f: f.write(newText)

Something like就像是

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

<do stuff with the result>
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)

If you are on linux and just want to replace the word dog with cat you can do:如果您使用的是 linux 并且只想用cat替换单词dog ,您可以执行以下操作:

text.txt:文本.txt:

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

Linux Command: Linux命令:

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原帖: https : //askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands

Using pathlib ( https://docs.python.org/3/library/pathlib.html )使用 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 .如果输入和输出文件不同,您可以为read_textwrite_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 .如果您想要比单个替换更复杂的更改,您可以将read_text的结果分配给一个变量,对其进行处理并将新内容保存到另一个变量,然后使用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.如果您的文件很大,您会更喜欢一种不读取内存中的整个文件的方法,而是逐行处理它,如 Gareth Davidson 在另一个答案中所示( https://stackoverflow.com/a/4128192/3981273 ) ,这当然需要使用两个不同的文件进行输入和输出。

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...最简单的方法是用正则表达式来做,假设你想遍历文件中的每一行('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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM