【问题标题】:Replace Text with Comma in File With Python [duplicate]用Python在文件中用逗号替换文本[重复]
【发布时间】:2015-10-03 14:28:04
【问题描述】:
#open file and rewrite (comma) to ,
with open('outputFile') as fo:
    fo.write(line.replace("(comma)"," , "))

我正在尝试将文本 (comma) 替换为文件中的文字 ,。当我运行上述代码时,出现以下错误:io.UnsupportedOperation: not writable

任何关于如何在文件中重写文本的见解将不胜感激。

我使用了下面的代码,它仍然不会用,替换(comma)

#open file and rewrite (comma) to , with open('outputFile.txt', "a+") as fo: fo.write(fo.replace('(comma)',',')) fo.close()

【问题讨论】:

    标签: python


    【解决方案1】:

    您收到“不可写”错误,因为您需要打开文件进行写入,通过将 mode 参数传递给 open 来完成:

    with open('outputFile', "w") as fo:
        fo.write(line.replace("(comma)"," , "))
    

    根据您想要的行为,您可能希望使用"w" 以外的模式,如果文件存在,它会截断文件。查看Python documentation on open了解更多详情。

    如果您仍然收到错误,则可能存在写入文件的权限问题。


    要实际对文件中的每一行执行替换,请查看 this questionthis question

    【讨论】:

    • line 来自哪里?
    • 在原帖中。
    • 据我了解,OP 正在读取、替换和写入同一个文件,在这种情况下,line 未定义。
    • 我上面编辑的新代码是否正确使用foline
    • 我添加了一些链接来回答如何在 Python 中对文件中的每一行执行替换;他们对这个问题的回答比我好得多。
    【解决方案2】:

    尝试以写入模式打开文件:

    with open('outputFile', 'w+') as fo:
        fo.write(line.replace("(comma)"," , "))
    

    【讨论】:

      【解决方案3】:

      fileinput 将允许您非常轻松地读取/写入同一个文件...

      with fileinput.input("out.txt") as fo:
           for line in file:
               print line.replace("(comma)"," , ")
      

      【讨论】:

        【解决方案4】:

        您需要使用“r+”参数以读/写模式打开文件。

        读取文件内容后,使用 seek(0) 和 truncate() 清除它,然后写入新文本。

        with open('outputFile', 'r+') as f:
            text = f.read()
            f.seek(0)
            f.truncate()
            f.write(text.replace('(comma)', ' , '))
        

        【讨论】:

          猜你喜欢
          • 2010-11-19
          • 1970-01-01
          • 1970-01-01
          • 2011-10-01
          • 1970-01-01
          • 2013-12-10
          • 2017-12-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多