Replace string within file contents

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

258219 次浏览
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','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)

差不多

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


<do stuff with the result>

最简单的方法是使用正则表达式进行迭代,假设您希望遍历文件中的每一行(存储‘ 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)

如果你想替换同一个文件中的字符串,你可能需要把它的内容读入一个局部变量,关闭它,然后重新打开它来写:

在这个示例中,我使用的是 和声明,它在 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语句更优雅地完成这项工作。

#!/usr/bin/python


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


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

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 命令:

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

使用 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的结果分配给一个变量,处理它并将新内容保存到另一个变量,然后用 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.