2016-09-20 141 views
0

嗨,我是一個Python初學者,並且不熟悉文件操作。我正在編寫一個用於日誌記錄的python腳本。以下是我的代碼段:使用Python中的時間戳創建文件夾

infile = open('/home/nitish/profiles/Site_info','r') 
lines = infile.readlines() 
folder_output =  '/home/nitish/profiles/output/%s'%datetime.now().strftime('%Y-%m-%d-%H:%M:%S') 
folder = open(folder_output,"w") 
for index in range(len(lines)): 
    URL = lines[index] 

    cmd = "curl -L " +URL 

    curl = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE) 

    file_data = curl.stdout.read() 
    print file_data 

    filename = '/home/nitish/profiles/output/log-%s.html'%datetime.now().strftime('%Y-%m-%d-%H:%M:%S') 
    output = open(filename,"w") 
    output.write(file_data) 
output.close() 
folder.close() 
infile.close() 

我不知道這是否正確。我希望每次腳本運行時都創建一個帶有時間戳的新文件夾,並將所有輸出從for循環放入具有時間戳的文件夾中。

感謝您的幫助提前

回答

0

您已經尾隨上所有的URL換行,這樣是行不通的,你會不會讓過去folder = open(folder_output,"w"),你要創建一個文件不是一個文件夾,也有不需要子進程。你可以做到這一切使用標準庫函數:

from os import mkdir 
import urllib.request 
from datetime import datetime 

now = datetime.now 

new_folder = '/home/nitish/profiles/output/{}'.format(now().strftime('%Y-%m-%d-%H:%M:%S')) 
# actually make the folder 
mkdir(new_folder) 

# now open the urls file and strip the newlines 
with open('/home/nitish/profiles/Site_info') as f: 
    for url in map(str.strip, f): 
     # open a new file for each request and write to new folder 
     with open("{}/log-{}.html".format(new_folder, now().strftime('%Y-%m-%d-%H:%M:%S')), "w") as out: 
      out.write(urllib.request.urlopen(url).read()) 

對於python2,使用import urllib和`了urllib.urlopen或更好,但使用requests