![](/img/trans.png)
[英]How to create a python list with the number of file in each sub directory of a directory
[英]Create file in sub directory 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()
在文件創建后移動文件,但是日期時間戳似乎有問題。
我是初學程序員,老實說我不知道如何處理這些問題。 我在考慮將變量分配給目錄和文件,但是日期時間讓我感到沮喪。
問題 :如果文件和子目錄的名稱/路徑不總是相同,如何在子目錄中創建文件?
將創建的目錄存儲在變量中。 如果該名稱存在目錄,則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:
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.