因为\ n而无法使用字符串?

时间:2014-11-11 07:50:26

标签: python

运行此代码时,由于字符串末尾的\ n,我收到错误。我该如何解决这个问题?

import urllib
prefix = 'http://archive.outernet.is/'
with open(!file_list.txt, 'r') as f:
    stock = f.read().splitlines()
    for l in stock:
        l = l.strip()
        content =   ("%s%s") % (prefix, l)
        print(content)
        urllib.request.urlretrieve(content, l)

文件列表包含

1.zip
2.zip
3.zip

错误代码类似于

Errno 2, no such file or directory 'website.ca/1.zip\n'

2 个答案:

答案 0 :(得分:1)

从每一行中删除空格:

for l in stock:
    l = l.strip()
    content =   ("%s%s") % (prefix, l)
    # etc. ...

答案 1 :(得分:0)

这是我正在运行的代码。

import urllib.request

prefix = 'http://archive.outernet.is/'
with open("input.txt", 'r') as f:
    stock = f.read().splitlines()
    for l in stock:
        content = ("%s%s") % (prefix, l)
        print(content)
        print(urllib.request.urlretrieve(content, l))

输出:

http://archive.outernet.is/003669cf61a1f17115b0bf74256114ea.zip
('003669cf61a1f17115b0bf74256114ea.zip', <httplib.HTTPMessage instance at 0x02362BC0>)
http://archive.outernet.is/0051d970f292ef8afb6d46102e90295e.zip
('0051d970f292ef8afb6d46102e90295e.zip', <httplib.HTTPMessage instance at 0x02362C10>)
http://archive.outernet.is/005f1d942b971216952437097d605cea.zip
('005f1d942b971216952437097d605cea.zip', <httplib.HTTPMessage instance at 0x02362C88>)
http://archive.outernet.is/006c514d4f3bf10bbff0e4152f8cae38.zip
...