2016-09-20 2 views
0

안녕하세요 저는 파이썬에서 초보자이며 파일 조작에 정통하지 않습니다. 로깅을위한 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() 

나는 이것이 정확한지 잘 모릅니다. 스크립트가 실행될 때마다 timestamp가있는 새 폴더를 만들고 for 루프의 모든 출력을 타임 스탬프가있는 폴더에 넣으려고합니다. 당신이 파일이 아닌 폴더를 만들려고로 사전에 도움을

감사합니다 당신이 작동하지 않을 수 있도록 모든 URL에 줄 바꿈을 후행 한

답변

0

, 당신도 있습니다, 과거 folder = open(folder_output,"w")을받지 않습니다 하위 프로세스가 필요 없습니다. 당신은 표준 lib 디렉토리 기능을 사용하여 모든 작업을 수행 할 수 있습니다, python2를 들어

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()) 

import urllib을 사용하고`urllib.urlopen 또는 더 나은 아직 사용 requests

관련 문제