[英]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'))
如果你想替換同一個文件中的字符串,你可能需要將它的內容讀入一個局部變量,關閉它,然后重新打開它以進行寫入:
我在這個例子中使用了 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
語句更優雅地完成這項工作。
#!/usr/bin/python with open(FileName) as f: newText=f.read().replace('A', 'Orange') with open(FileName, "w") as f: f.write(newText)
就像是
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)
如果您使用的是 linux 並且只想用cat
替換單詞dog
,您可以執行以下操作:
文本.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_text
和write_text
使用兩個不同的變量。
如果您想要比單個替換更復雜的更改,您可以將read_text
的結果分配給一個變量,對其進行處理並將新內容保存到另一個變量,然后使用write_text
保存新內容。
如果您的文件很大,您會更喜歡一種不讀取內存中的整個文件的方法,而是逐行處理它,如 Gareth Davidson 在另一個答案中所示( https://stackoverflow.com/a/4128192/3981273 ) ,這當然需要使用兩個不同的文件進行輸入和輸出。
最簡單的方法是用正則表達式來做,假設你想遍歷文件中的每一行('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.