url csv文件下载列表python IOError:[Errno 22]
我有下面的代码。在下载任何csv文件之前,我一直收到一个错误。USW0000100.csv是第一个csv文件名。我不知道为什么我会出错。我的文件名中似乎没有任何不受支持的字符url csv文件下载列表python IOError:[Errno 22],python,csv,url,Python,Csv,Url,我有下面的代码。在下载任何csv文件之前,我一直收到一个错误。USW0000100.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 rig
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\usw0000100.csv\n'问题可能是文件名末尾的换行符。当您从CSV中读取该行时,它包括换行符。有几种方法可以解决这个问题 你可以像这样简单地从末尾去掉换行符
raw_name = url.rsplit('/', 1)[-1]
name = raw_name.strip()
# your code here
另一种方式,简洁实用的风格(谢谢@fenceop)
从名称中删除\n如果我执行“打印文件名”,则显示时不带\n。C:/py测试/下载\usw0000100.csv。不过我会试试的。
for url in map(str.strip, file):
# your code here