2013-08-30 40 views
0

我想實現在此給出了答案:就地文件的字符串替換 - Windows錯誤

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') 

我ge t出現以下錯誤:

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 

我在做什麼明顯錯誤?

回答

1

不是傳遞文件的對象,傳遞文件名(或文件名列表)的fileinput.input

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

注意:不要使用file作爲變量名,file是一個內置在功能。

1

什麼:

import fileinput 
a = 'zzz.txt' 

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