我试图从 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+")
Run Code Online (Sandbox Code Playgroud)
对于第一个文件,这总是失败:
$ : ./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'
Run Code Online (Sandbox Code Playgroud)
任何想法缺少什么?
我相信问题在于文件模式 a+ 将创建文件,如果它不存在,而不是目录。您将不得不编写自定义代码来从路径中分割文件名的行(或者最好仍然使用 os.path :https://docs.python.org/2/library/os.path.html,甚至可能os.path.dirname(path)
警惕在系统中创建随机路径的安全考虑。验证路径是否在特定沙箱内(考虑有人在您的文件中放入一个条目../../或/etc/passwd让您附加随机用户数据..os.path.abspath可能很有用 - 出于这个原因,我对粘贴只会创建随机目录的代码持谨慎态度你复制和粘贴而不考虑这种影响。