对你所经历的行为的一个可能的解释是
不清理输入linewith open ('/tmp/reddy_log.txt') as infile:
...
for line in infile:
...
myurl = "http://data.xyz.com" + str(line)
wget.download(str(myurl))
当您迭代一个file对象时,(for line in infile:)字符串
您得到的是一个换行符('\n')结束的-如果您没有
在使用line之前删除换行符,哦,好吧,换行符
在你使用line产生的东西中仍然存在
为了说明这一概念,请看一下文字记录
我做过的测试08:28 $ cat > a_file
a
b
c
08:29 $ cat > test.py
data = open('a_file')
for line in data:
new_file = open(line, 'w')
new_file.close()
08:31 $ ls
a_file test.py
08:31 $ python test.py
08:31 $ ls
a? a_file b? c? test.py
08:31 $ ls -b
a\n a_file b\n c\n test.py
08:31 $
如您所见,我从文件中读取行并使用
line作为文件名,猜猜看,ls列出的文件名
最后有一个?但是我们可以做得更好,正如在
精细手册第页,共页ls-b, escape
print C-style escapes for nongraphic characters
而且,正如您在ls -b的输出中看到的,文件名不是
以问号结尾(这只是默认使用的占位符
但以换行符结尾。在
我要说的是,你应该避免使用
存储计算的中间结果的临时文件。在
Python的一个很好的特性是存在生成器表达式,
如果你想,你可以写你的代码如下
^{pr2}$
不要被注释的数量所迷惑,我的代码只是没有注释import wget
from my_constants import error_column
lines = (line.rstrip() for line in open('whatever.csv'))
all_tokens = (line.split() for line in lines if line)
targets = (tokens[payload_column] for tokens in all_tokens if tokens[error_column]=='200')
for target in targets: wget.download(target)