【问题标题】:I need to open and rewrite a line in a file in Python [duplicate]我需要在 Python 中打开并重写文件中的一行 [重复]
【发布时间】:2012-11-28 07:08:13
【问题描述】:

可能重复:
Search and replace a line in a file in Python
How do I modify a text file in Python?

我有一个输入文件,我需要在运行程序之前使用需要修改的不同文件来重写它。我在这里尝试了各种解决方案,但似乎没有一个有效。我最终只是用一个空白文件覆盖了我的文件

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

或者使用该代码,例如每次运行程序时我更改的名称都不同,因此我需要替换整行而不仅仅是一个关键字

【问题讨论】:

标签: python file


【解决方案1】:

一种简单的方法可能是将文本读入字符串,然后将字符串与要写入的文本连接起来:

infile = open('hey.txt','r+')
content = infile.read()
text = ['foo','bar']
for item in text:
     content +=item  #adds 'foo' on first iteration, 'bar' on second
infile.write(content)
infile.close()

或者改变一个特定的关键词:

infile = open('hey.txt','r+')
content = infile.read()
table = str.maketrans('foo','bar')
content = content.translate(table)  #replaces 'foo' with 'bar'
infile.write(content)
infile.close()

或逐行更改,您可以使用 readlines 并将每一行作为列表的索引:

infile = open('hey.txt','r+')
content = infile.readlines() #reads line by line and out puts a list of each line
content[1] = 'This is a new line\n' #replaces content of the 2nd line (index 1)
infile.write(content)
infile.close()

也许不是一种特别优雅的解决问题的方法,但它可以封装在一个函数中,并且“文本”变量可以是多种数据类型,如字典、列表等。还有很多替换文件中每一行的方法,它仅取决于更改行的条件(您是在行中搜索字符还是单词?您是否只是想根据文件中的位置替换行?)--所以这些也是需要考虑的一些事情。

编辑:在第三个代码示例中添加引号

【讨论】:

  • .translate(table) 将替换 fbor... 与声明和来自str.replace 的行为绝对不同...
  • 使用with 语句打开文件是值得的——它有很多优点,没有缺点。
  • 乔恩,你是对的,对此感到抱歉。不要使用 translate 方法!
  • 我认为你的最后一个应该可以工作!谢谢
  • 当我运行时我收到infile.write(content) TypeError: expected a character buffer object
【解决方案2】:

虽然丑陋,但这个解决方案最终会奏效

infile = open('file.txt', 'r+')
content = infile.readlines() #reads line by line and out puts a list of each line
content[1] = "foo \n" #replaces content of the 2nd line (index 1)
infile.close
infile = open('file.txt', 'w') #clears content of file. 
infile.close
infile = open('file.txt', 'r+')
for item in content: #rewrites file content from list 
    infile.write("%s" % item)
infile.close()

感谢大家的帮助!!

【讨论】:

    猜你喜欢
    • 2010-12-28
    • 1970-01-01
    • 2019-01-20
    • 2014-06-02
    • 2015-10-01
    • 2018-05-31
    • 1970-01-01
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多