2017-10-14 36 views
-4

我必須在一個文件中搜索一個字符串(比如str1),並用另一個字符串(比如str2)替換它。 2個字符串的搜索(str1)和寫入(str2)將在同一個文件中完成。請有人爲此提出一些方法或邏輯。如何在一個文件中使用python搜索一個字符串(比如str1)並用另一個字符串(比如str2)替換它?

+0

我有點相信這是重複...不知道現在該怎麼證明這一點...... 順便說一句那你試試? – efkin

+0

你問Google之前「在文件python中搜索並替換字符串」嗎? –

+1

[用Python代替文件中的文本]的可能重複(https://stackoverflow.com/questions/13089234/replacing-text-in-a-file-with-python) –

回答

0

下面的代碼將做到這一點的任務:

FILE = r'A:\some\sort\of\floppy\file.txt' # The target file. 
str1 = '\n' 
str2 = '\r\n' 

data = '' 

with open(FILE) as f: # Comment the "with" block under Python 2.6 
    data = f.read() 
# Uncomment lines below if the "with" statement is commented 
##f = open(FILE) 
##data = f.read() 
##f.close() 
data = data.replace(str1, str2) 

with open(FILE, 'w') as f: # Same as for previous "with" 
    f.write(data) 
# And here too 
##f = open(FILE) 
##f.write(data) 
##f.close() 
相關問題