在Python中创建新文件导致FileNotFoundError错误。

8
我正在尝试使用Python 3从文件名列表中创建一组随机文件。
#!/usr/local/bin/python3

import random
import sys

random.seed()

print("Reading lines from ", sys.argv[1])

linecount = 0
lines = []
with open(sys.argv[1]) as f:
    for line in f:
         lines.append(line)

filelist = random.sample(lines, 5);
for newfile in filelist:
    print("Touching file ", newfile)
    open(newfile.rstrip(), "a+")

这总是在处理第一个文件时失败,出现以下错误信息:
$ : ./file-gen.py files.txt
Reading lines from  files.txt
Touching file  62/6226320DE.pdf

Traceback (most recent call last):
  File "./file-gen.py", line 19, in <module>
    open(newfile.rstrip(), "a+");
FileNotFoundError: [Errno 2] No such file or directory: '62/6226320DE.pdf'

有什么想法是缺失的吗?
2个回答

8
我认为问题在于文件模式a+会创建文件,但不会创建目录。您需要编写自定义代码来从路径中分离文件名的行(最好使用os.path:https://docs.python.org/2/library/os.path.html,甚至可能是os.path.dirname(path))。
请查看:如何检查目录是否存在并在必要时创建它? 创建随机路径时,请注意安全考虑。验证路径是否在特定沙箱内(考虑有人在您的文件中放置一个条目 ../..//etc/passwd 来让您附加随机用户数据。 os.path.abspath可以是有用的 - 因此,我对粘贴只会创建随机目录的代码持谨慎态度,而不考虑其影响。

0
我建议首先尝试打开一个特定的文件,而不是从输入中随机选择一组文件,以排除权限和路径问题。
您还应该尝试打印os.path.getcwd(),以确保您在那里具有写入权限。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接