2015-09-02 15 views
1

我試着從文件名列表在python創建一個隨機文件集3.使用Python創建新的文件會導致FileNotFoundError

#!/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' 

任何想法缺少什麼?

回答

1

我相信問題是文件模式a +將創建文件,如果它不存在,但不是目錄。你將不得不編寫自定義代碼從路徑拆分文件名的行(或更好的使用os.path中:https://docs.python.org/2/library/os.path.html,甚至os.path.dirname(path)

看一看:How to check if a directory exists and create it if necessary?

警惕安全在你的系統中創建隨機路徑的考慮因素驗證路徑是否在特定的沙箱內(考慮有人在你的../..//etc/passwd文件中輸入一個條目來讓你附加隨機用戶數據。os.path.abspath可能是有用的 - 因爲這個原因,我謹慎的粘貼代碼,只需創建隨機目錄,然後複製並粘貼即可,而不必考慮效果。

+1

創建目錄首先解決了問題。 – BetaRide

0

我建議作爲第一步嘗試打開一個特定的文件,而不是從輸入中隨機設置一組文件以排除權限和路徑問題。

您還應該嘗試打印os.path.getcwd()以確保您有寫入權限。

相關問題