python中使用时间戳创建文件夹

2024-04-26 00:57:51 发布

您现在位置: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循环的所有输出放入带有时间戳的文件夹中。在

提前谢谢你的帮助


Tags: 脚本homecloseoutputdatadatetimeopenfolder
1条回答
网友
1楼 · 发布于 2024-04-26 00:57:51

在所有的url上都有尾随的换行符,这样就不起作用了,您不会越过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

相关问题 更多 >