您好我是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 :(得分:1)
您在所有网址上都有跟踪换行符,因此无法使用,当您尝试创建文件而不是文件夹时,您不会超过folder = open(folder_output,"w")
,也不需要子流程。您可以使用标准的lib函数完成所有操作:
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