![](/img/trans.png)
[英]Python: search for a STR1 in a line and replace the whole line with 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.