【问题标题】:Inplace file string replacement - windows error就地文件字符串替换 - Windows 错误
【发布时间】:2023-04-02 17:59:01
【问题描述】:

我正在尝试实现这里给出的答案:

https://stackoverflow.com/a/1388570/1461850

我有一个输入文件zzz.txt,其中包含:

potato potato potato potato potato potato potato potato potato 
potato potato potato
potato potato potato potato potato potato potato potato potato
potato potato potato potato turnip potato
potato potato parsnip potato potato potato

我正在尝试像这样替换单词:

import fileinput
fileinput.close()
file = open('zzz.txt', "r+")
for line in fileinput.input(file, inplace=1):
    print line.replace('turnip', 'potato')

我收到以下错误:

Traceback (most recent call last):
  File "testss.py", line 19, in <module>
    for line in fileinput.input(file, inplace=1):
  File "c:\python27\lib\fileinput.py", line 253, in next
    line = self.readline()
  File "c:\python27\lib\fileinput.py", line 322, in readline
    os.rename(self._filename, self._backupfilename)
WindowsError: [Error 123] The filename, directory name, or volume label syntax i
s incorrect

我做错了什么吗?

【问题讨论】:

    标签: python windows string file


    【解决方案1】:

    不传递文件对象,而是将文件名(或文件名列表)传递给fileinput.input

    fileinput.input('zzz.txt', inplace=1):
    

    注意:不要使用file作为变量名,file是一个内置函数。

    【讨论】:

      【解决方案2】:

      怎么样:

      import fileinput
      a = 'zzz.txt'
      
      for line in fileinput.input(a, inplace=1):
          print line.replace('turnip', 'potato')
      

      【讨论】:

        猜你喜欢
        • 2015-01-27
        • 1970-01-01
        • 2012-04-19
        • 2020-11-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多