【问题标题】:download list of url csv files python IOError: [Errno 22]下载 url csv 文件列表 python IOError: [Errno 22]
【发布时间】:2018-04-27 13:49:27
【问题描述】:

我在下面有以下代码。 Credit to this answer. 在下载任何 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\n'

【问题讨论】:

  • 从名称中去掉 \n
  • 如果我执行“打印文件名”,它会显示没有 \n。 C:/py-testing/downloads\USW00000100.csv。不过我会试试的。

标签: python csv url


【解决方案1】:

问题可能是文件名末尾的换行符。当您从 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-29
    • 2014-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-15
    相关资源
    最近更新 更多