Reputation: 23
I am getting some strange behavior using the fileinput
python module. If the file I am trying to alter does not have user read access, it gets deleted.
import fileinput
try:
for line in fileinput.input('TEST', inplace=1):
line = line.strip()
if '/' in line:
print "PATH: " + line
else:
print line
except Exception as e:
print e
If I run this file, I get:
$ ls -l
--wxrwxrwx 1 myusername agqt3 0 Feb 25 11:02 TEST
$ python test.py
[Errno 13] Permission denied: 'TEST.bak'
$ ls -l
total 0
The file gets deleted. The same thing occurs with every other combination of permission bits that do not include the user r
. I have reproduced this in bash
, csh
and ksh
.
Upvotes: 2
Views: 1026
Reputation: 43832
You seem to be using inplace=1
, so yes the file is expected to be overwritten.
When this is done a .bak
file is created, and the initial file name overwritten.
However, you do not have permissions to read the inital file (but can write), so when the backup is created it is empty (or fails), and the original overwritten.
From the inplace documentation: http://docs.python.org/2/library/fileinput.html#fileinput.FileInput
Optional in-place filtering: if the keyword argument inplace=1 is passed to fileinput.input() or to the FileInput constructor, the file is moved to a backup file and standard output is directed to the input file (if a file of the same name as the backup file already exists, it will be replaced silently). This makes it possible to write a filter that rewrites its input file in place. If the backup parameter is given (typically as backup='.'), it specifies the extension for the backup file, and the backup file remains around; by default, the extension is '.bak' and it is deleted when the output file is closed. In-place filtering is disabled when standard input is read.
Upvotes: 1
Reputation: 85035
Looks like a bug in fileinput
. Suggest you open an issue about it on the Python Bug Tracker
Upvotes: 0