gpt4 book ai didi

python - fileinput.py 删除目标文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:16:47 24 4
gpt4 key购买 nike

我在使用 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 的所有其他权限位组合,也会发生同样的事情。我已经在 bashcshksh 中复制了它。

最佳答案

您似乎正在使用 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.

关于python - fileinput.py 删除目标文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15060466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com