在我的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()
在創建文件後移動文件,但日期時間標記似乎會造成問題。
我是一個初學者程序員,我真的不知道如何解決這些問題。我正在考慮將變量分配給目錄和文件,但是日期時間讓我沮喪。
問題:如果文件和子目錄的名稱/路徑不總是相同,如何在子目錄中創建文件?