簡體   English   中英

如何使用python在文件中搜索字符串(比如str1)並將其替換為另一個字符串(比如str2)?

[英]How to search a string(say str1) and replace it with another string(say str2) in a file using python?

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

以下代碼將完成該任務:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM