下载 url csv 文件列表 python IOError: [Errno 22]



我在下面有以下代码。感谢这个答案。在下载任何csv文件之前,我不断收到错误。USW00000100.csv 是第一个 csv 文件名。我不确定为什么会出现错误。我的文件名中似乎没有任何不受支持的字符。

import os
import urllib
DOWNLOADS_DIR = "C:/py-testing/downloads"
# For every line in the file
for url in open("C:/py-testing/urls.txt"):
    # Split on the rightmost / and take everything on the right side of that
    name = url.rsplit('/', 1)[-1]
    # Combine the name and the downloads directory to get the local filename
    filename = os.path.join(DOWNLOADS_DIR, name)
    urllib.urlretrieve(url, filename)

错误:

IOError: [Errno 22] 无效模式 ('wb'( 或文件名: 'C:/py-testing/downloads\USW00000100.csv'

问题可能是文件名末尾的换行符。当您从 CSV 中读入的行时,它包括换行符。有几种方法可以解决这个问题。

您可以像这样简单地从末尾剥离换行符。

raw_name = url.rsplit('/', 1)[-1]
name = raw_name.strip()
# your code here

另一种方式,具有更简洁的功能风格(谢谢@fenceop(

for url in map(str.strip, file): 
    # your code here

相关内容

最新更新