Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
创建时的Python wierd文件名_Python - Fatal编程技术网

创建时的Python wierd文件名

创建时的Python wierd文件名,python,Python,我有一个包含html/doc文件列表的txt文件,我想使用python下载它们,并将它们保存为1.html、2.doc、3.doc等 http://example.com/kran.doc http://example.com/loj.doc http://example.com/sks.html 我已经成功地创建了功能齐全的脚本,除了python会在新创建的文件末尾添加问号(如果您从linux查看),如果您从windows查看,则文件名类似于5CFB43~X import urllib2 s

我有一个包含html/doc文件列表的txt文件,我想使用python下载它们,并将它们保存为1.html、2.doc、3.doc等

http://example.com/kran.doc
http://example.com/loj.doc
http://example.com/sks.html
我已经成功地创建了功能齐全的脚本,除了python会在新创建的文件末尾添加问号(如果您从linux查看),如果您从windows查看,则文件名类似于5CFB43~X

import urllib2
st = 1;
for line in open('links.txt', 'r'):
        u = urllib2.urlopen(line)
        ext = line.split(".")
        imagefile = str(st)+"."+ext[-1]
        #file created should be something.doc but its something.doc? -> notice question mark
        fajl = open(imagefile, "w+")
        fajl.write(u.read())
        fajl.close()
        print imagefile
        st += 1
行终止符是两个字符,而不是一个

for line in open('links.txt', 'rU'):
但不再是了。

行终止符是两个字符,而不是一个

for line in open('links.txt', 'rU'):

但现在不是了。

这是因为以这种方式读取的行将以
'\n'
结尾,因此是

只需在循环的开头添加以下内容:

if line.endswith('\n'):
    line = line[:-1]
或者正如AKX在评论中指出的那样,只是:

line = line.rstrip('\r\n')

因此,您可以覆盖任何类型的行尾。

这是因为以这种方式读取的行尾将以
'\n'
结尾,因此是

只需在循环的开头添加以下内容:

if line.endswith('\n'):
    line = line[:-1]
或者正如AKX在评论中指出的那样,只是:

line = line.rstrip('\r\n')

因此,您可以覆盖任何类型的行尾。

处理
line.strip()
而不是
line

处理
line.strip()
而不是
line

为什么不在没有
if
子句的情况下处理
line=line.rstrip(\r\n”)
?它感觉更优雅。这很好用,谢谢:)我可以接受的时候会接受为什么不带
if
子句的
line=line.rstrip(“\r\n”)
?它感觉更优雅。这是完美的工作感谢:)将接受当我可以