【问题标题】:FileNotFoundError: [Errno 2]: Variable Filenames with open()FileNotFoundError:[Errno 2]:带有 open() 的变量文件名
【发布时间】:2018-04-13 18:30:24
【问题描述】:

我正在开发一个 Python 中的 webscraper,它从 xml 文件中获取名称和下载链接。首先,它连接来自 date、hof 和 az 的名称。然后它应该下载 ziplink (www.file.io/xyzfile.zip) 后面的文件,并将其保存在同一目录中的串联名称下。

除非它不会使用我的串联名称。因此,一般的问题是:我需要提供哪些确切信息作为函数的参数?使用 type() 我确保我会提供一个字符串,但它不会接受它。

import requests
from bs4 import BeautifulSoup
xml = requests.get('https://www.rechtsprechung-im-internet.de/rii-toc.xml')
soup = BeautifulSoup(xml.text, 'xml')

for item in soup.find_all('item'):
    ziplink=str(item.link.text) 
    datum=str(item.find('entsch-datum').text)
    az=str(item.aktenzeichen.text)
    hof=str(item.gericht.text)
    name=datum+'-'+hof+'-'+az
    print(type(name))
    r=requests.get(ziplink, allow_redirects=True)
    with open('%s.zip' % name,'wb') as f:
        f.write(r.content)
    print(name)

但不幸的是,我收到以下错误:

Traceback (most recent call last):
  File "simple_script.py", line 26, in <module>
    with open('%s.zip' % name,'wb') as f:
FileNotFoundError: [Errno 2] No such file or directory: '20100114-BGH 9. Zivilsenat-IX ZB 72/08.zip'

使用 print(type()) 我确保我提供了一个字符串作为名称参数。因为当我使用name = 'test.zip' 测试代码时,它运行良好。但理想情况下,我想动态命名文件。

这是我在 Stackoverflow 上的第一篇文章,我很想得到一些反馈。太感谢了!

干杯,贾斯珀

【问题讨论】:

    标签: xml python-3.x web-scraping io


    【解决方案1】:

    你试过在open函数中使用“wb+”权限吗?

    with open('%s.zip' % name,'wb+') as f:
        f.write(r.content)
    

    + 表示如果找不到文件,它应该创建文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 2020-12-31
      • 2012-08-25
      • 1970-01-01
      相关资源
      最近更新 更多