【问题标题】:How to open a file and change a line如何打开文件并更改行
【发布时间】:2016-01-21 00:58:26
【问题描述】:

我已经查看了很多关于此的主题,但找不到正确的答案:

我对 python 有点陌生。我在python中打开一个文件,在开始行之前插入一行,在最后一行之前插入一行,然后在最后将所有行重构为一个字符串变量。

这是我试图在打开的文件上运行的功能。这会将 mode="0" 的所有行更改为 mode="1",反之亦然。

def Modes(file, mode):
    endstring = ''
    if(mode == 1):
        mode0 = 'mode="0"'
        mode1 = 'mode="1"'
    else:
        mode0 = 'mode="1"'
        mode1 = 'mode="0"'   
    for line in iter(file):
        if 'Modes' in line:
            line = line.replace(mode0,mode1)
        endstring += line
    return endstring

所以我尝试以下方法:

  mode = 1
  input_file = open("c:\myfile.txt")
  input_file.readlines()
  lengthlines = len(input_file)
  #insert line at position 1
  input_file.insert(1,'<VARIABLE name="init1" />')
  #insert line at last line position - 1
  input_file.insert(lengthlines,'<VARIABLE name="init2" />')
  #join the lines back up again
  input_file = "".join(input_file)
  #run the modes function - to replace all occurrences of mode=x
  finalfile = Modes(input_file,mode)
  print finalfile

然后我收到错误,“文件类型的对象,没有“len()””和一般对象/列表错误。

我似乎把对象/列表等弄混了,但我不确定在哪里 - 将不胜感激任何帮助 - 干杯

【问题讨论】:

  • input_file.readlines() 本身并没有做任何事情
  • 我弄错了,我已经更新了:/ 抱歉

标签: python readlines


【解决方案1】:

input_file.readlines() 返回内容但不将其分配给 input_file。 您必须将调用的返回值分配给一个变量,如下所示:

file_content = input_file.readlines()

然后将其传递给 len()

lengthlines = len(file_content)

编辑:使用 len() 解决问题会导致更多异常。 这应该大致做你想要的:

mode = 1
with open("c:\myfile.txt") as input_file:
    file_content = list(input_file.readlines())
file_content.insert(0,'<VARIABLE name="init1" />')
file_content.append('<VARIABLE name="init2" />')
finalfile = Modes(file_content,mode)
print finalfile

如果您想坚持多行,您可能必须更改函数中的字符串连接。

    endstring += line + '\n'
return endstring.rstrip('\n')

虽然这还没有将新内容写回文件。

EDIT2:完成文件后关闭文件总是一个好习惯,因此我更新了上面的内容以使用处理此问题的上下文管理器。你也可以在完成后显式调用input_file.close()

【讨论】:

  • 不要使用file_content.insert(lengthlines,'&lt;VARIABLE name="init2" /&gt;')添加到列表的末尾,您应该使用file_content.append('&lt;VARIABLE name="init2" /&gt;')
  • @Mitch Pomery 是的,完全有道理,也不需要 len()。我会更新的。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多