简体   繁体   English

如何使用python在文件中搜索字符串(比如str1)并将其替换为另一个字符串(比如str2)?

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

I have to search a string(say str1) in a file and replace it with another string(say str2) in that same file.我必须在文件中搜索一个字符串(比如 str1),然后用同一个文件中的另一个字符串(比如 str2)替换它。 The searching(of str1) and writing(of str2) of the 2 strings will be done on the same file. 2 个字符串的搜索(str1)和写入(str2)将在同一个文件中完成。 Please someone suggest some methods or logic for this.请有人为此提出一些方法或逻辑。

The following code will do that task:以下代码将完成该任务:

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.

相关问题 Python:在一行中搜索STR1并将整行替换为STR2 - Python: search for a STR1 in a line and replace the whole line with STR2 逻辑表达式:为什么“str1 in str2 or str2 not in str1”为我的打印语句返回 True? - Logical Expressions: Why does “str1 in str2 or str2 not in str1” return True for my print statement? <function> (str1,str2)分别调用它们 - <function>(str1, str2) calling them separately 我怎么说如果name!= str:print(“那不是名字”)python 3 - How do i say if name != str: print(“thats not a name”) python 3 如何在Python中使用str使用str将异常对象转换为字符串? - How to use str to convert an exception object to string using str in Python? 如何让 python 检查一个字符串是否可以说 text1 在这个文件中? - How to make python check if a string lets say text1 is in this file? 使用str.replace替换字符串中位于不同字符串占位符的字母 - Using str.replace to replace letters in a string at different placeholders of the string 如何在 Python 中使用 str.format 截断字符串? - How to truncate a string using str.format in Python? 给定 2 个字符串(DNA 序列),它会返回一个布尔值,以显示 str1 中是否存在与 str2 的片段配对的长度 &gt;=5 的连续子片段 - Given 2 strings, (DNA sequences), it retrns a bool to show if a contigus sub-fragm of length >=5 exists in str1 that pairs to a fragment of str2 如何在python中使用str(a [i])将数组转换为字符串 - How do I convert a array into a string using str(a[i]) in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM