就地文件字符串替换-Windows错误

问题描述:

我正在尝试实现此处给出的答案:

I am trying to implement the answer given here:

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

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

I have an input file zzz.txt containing:

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

我正在尝试用这样的方式替换单词:

I am trying to replace words inplace like so:

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

我做错了什么吗?

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

Instead of passing the file object, pass the file name(or list of filenames) to fileinput.input:

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

注意:请勿使用 file 作为变量名, file 是内置函数.

Note: Don't use file as a variable name, file is a built-in function.