Skip to main content
 首页 » 编程设计

python之fileinput.py 删除目标文件

2025年05月04日6shanyou

我在使用 fileinput python 模块时遇到了一些奇怪的行为。如果我尝试更改的文件没有用户读取权限,它将被删除。

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 

如果我运行这个文件,我会得到:

$ 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 

文件被删除。对于不包括用户 r 的所有其他权限位组合,也会发生同样的事情。我已经在 bash、csh 和 ksh 中复制了它。

请您参考如下方法:

您似乎正在使用 inplace=1,所以是的,该文件预计会被覆盖。 完成后,将创建一个 .bak 文件,并覆盖初始文件名。

但是,您没有读取初始文件的权限(但可以写入),因此创建备份时它是空的(或失败),并且原来的覆盖。

来自 inplace 文档: 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.