【问题标题】:How to search a string(say str1) and replace it with another string(say str2) in a file using python?如何使用python搜索一个字符串(比如str1)并将其替换为文件中的另一个字符串(比如str2)?
【发布时间】:2017-10-14 08:04:20
【问题描述】:

我必须在一个文件中搜索一个字符串(比如 str1),然后用同一个文件中的另一个字符串(比如 str2)替换它。两个字符串的搜索(str1)和写入(str2)将在同一个文件上完成。请有人为此提出一些方法或逻辑。

【问题讨论】:

  • 我有点确定这是重复的...现在不知道如何证明...顺便说一句,您尝试了什么?
  • 在询问之前您是否在 Google 上“搜索并替换文件 python 中的字符串”?
  • 您的问题在当前状态下相当广泛。如果您发布一些您编写的代码并询问有关它的特定问题,那将是很好的。但我要提一下,通常的做法是修改原始文件,而是制作一个新文件,并在保存新文件后删除旧文件(如有必要)。否则,如果发生不良情况(例如断电),您可能会丢失数据。

标签: python


【解决方案1】:

以下代码将完成该任务:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-29
    • 2016-11-13
    • 2020-01-06
    • 2022-08-17
    • 2012-07-17
    • 2018-05-19
    • 1970-01-01
    • 2020-02-12
    相关资源
    最近更新 更多