如何编写文件名以在python中使用URL名称?

时间:2019-07-12 01:52:57

标签: python

我对一个大型URL文件进行了API扫描,读取了该URL并以JSON格式获取了结果

我得到了类似的网址和域

google.com
http://c.wer.cn/311/369_0.jpg

如何使用url名称“ .format(url_scan,日期)”更改文件格式名称

如果我使用人工名称并且成功创建了一个文件,但是我想使用它从用于文件名的URL文本文件中读取所有URL名称

域名用于json文件名并成功创建,没有错误

dates = yesterday.strftime('%y%m%d')
savefile = Directory + "HTTP_{}_{}.json".format(url_scan,dates) 
out = subprocess.check_output("python3 {}/pa.py -K {} "
                          "--sam '{}' > {}"     
                    .format(SCRIPT_DIRECTORY, API_KEY_URL, json.dumps(payload),savefile ), shell=True).decode('UTF-8') 
result_json = json.loads(out)
with open(RES_DIRECTORY + 'HTTP-aut-20{}.csv'.format(dates), 'a') as f:
      import csv 
       writer = csv.writer(f) 
      for hits in result_json['hits']: 
             writer.writerow([url_scan, hits['_date']) 
             print('{},{},{}'.format(url_scan, hits['_date']))

仅当使用http url名称写入json文件名时显示的错误 所以目录不是问题

每个/所显示的内容都被系统解释为目录

[Errno 2] No such file or directory: '/Users/tes/HTTP_http://c.wer.cn/311/369_0.jpg_190709.json'

1 个答案:

答案 0 :(得分:1)

大多数(如果不是全部)操作系统不允许字符:/在文件名中使用,因为它们在URL字符串中具有特殊含义。这就是为什么它给您一个错误。

您可以这样替换这些字符,例如:

filename = 'http://c.wer.cn/311/369_0.jpg.json google.com.json'
filename = filename.replace(':', '-').replace('/', '_')