0

I am trying to implement the answer given here:

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

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

I get the following error:

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

Am I doing something obviously wrong?

Community
  • 1
  • 1
Lee
  • 29,398
  • 28
  • 117
  • 170

2 Answers2

1

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

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

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

Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
1

What about:

import fileinput
a = 'zzz.txt'

for line in fileinput.input(a, inplace=1):
    print line.replace('turnip', 'potato')
badc0re
  • 3,333
  • 6
  • 30
  • 46