就地文件stringreplace – Windows错误

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

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

我有一个input文件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 

我试图用这样的词replace词:

 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 

我在做什么明显错误?

Solutions Collecting From Web of "就地文件stringreplace – Windows错误"

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

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

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

关于什么:

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