2013-08-22 53 views
3

在我的Python腳本中,我需要在不更改目錄的情況下在子目錄中創建一個新文件,並且我需要不斷地從當前目錄編輯該文件。在子目錄Python中創建文件?

我的代碼:

os.mkdir(datetime+"-dst") 

for ip in open("list.txt"): 
    with open(ip.strip()+".txt", "a") as ip_file: #this file needs to be created in the new directory 
     for line in open("data.txt"): 
      new_line = line.split(" ") 
      if "blocked" in new_line: 
       if "src="+ip.strip() in new_line: 
        #write columns to new text file 
        ip_file.write(", " + new_line[11]) 
        ip_file.write(", " + new_line[12]) 
        try: 
         ip_file.write(", " + new_line[14] + "\n") 
        except IndexError: 
         pass 

問題

的目錄和文件不會總是相同的,這取決於服務器我運行該腳本的路徑。目錄名稱的一部分將是它創建時的日期時間,即time.strftime("%y%m%d%H%M%S") + "word",如果時間不斷變化,我不確定如何調用該目錄。我認爲我可以使用shutil.move()在創建文件後移動文件,但日期時間標記似乎會造成問題。

我是一個初學者程序員,我真的不知道如何解決這些問題。我正在考慮將變量分配給目錄和文件,但是日期時間讓我沮喪。

問題:如果文件和子目錄的名稱/路徑不總是相同,如何在子目錄中創建文件?

回答

9

將創建的目錄存儲在變量中。 os.mkdir如果目錄以該名稱存在,則拋出。 使用os.path.join將路徑組件連接在一起(它知道是使用/還是\)。

import os.path 

subdirectory = datetime + "-dst" 
try: 
    os.mkdir(subdirectory) 
except Exception: 
    pass 

for ip in open("list.txt"): 
    with open(os.path.join(subdirectory, ip.strip() + ".txt"), "a") as ip_file: 
     ... 
0

第一時間值轉換的東西的文件夾名稱可以使用 像這可能是工作 mydate_str = datetime.datetime.now()的strftime( 「%間%D-%Y」)

然後創建一個文件夾需要 - 退房 Creating files and directories via Python Johnf