读取文件,解压缩url并重新编写-Python

时间:2013-06-16 06:14:40

标签: python url

我正在阅读以下format(a.txt)中的文字文件。

http://www.example.com/forum/showthread.php?t=779689/images/webcard.jpg 121.10.208.31

然后我只需要使用www.example.com获取/images/webcard.jpg 121.10.208.31部分并写入相同的文件或单独的文件。在这种情况下,我将其写入b.txt

from urlparse import urlparse 
f = open('a.txt','r')
fo = open('b','w')


for line in f:
    fo.write(urlparse(line).netloc+ ' ' + line.split(' ')[1] + ' ' + line.split(' ')[2] + '\n')

上面的代码给出了以下错误?如何实现?

    Traceback (most recent call last):
  File "prittyprint.py", line 17, in <module>
    fo.write(urlparse(line).netloc+ ' ' + line.split(' ')[1] + ' ' + line.split(' ')[2] + '\n')
IndexError: list index out of range

1 个答案:

答案 0 :(得分:3)

可能是您的文件a.txt中存在例外情况。某些行可能没有此格式。你可以试试这个 -

from urlparse import urlparse 

f = open('a.txt','r')
fo = open('b','w')

for line in f:
    split_line = line.split(' ')
    if len(split_line) >=3:
        fo.write(urlparse(line).netloc+ ' ' + split_line[1] + ' ' + split_line[2] + '\n')
    else:
        print "ERROR: some other line: %s" % (line) #continue on with next line