为什么我的代码删除整个文本文件而不是行?

时间:2016-03-09 09:36:24

标签: python file urllib2

我正在检查http代码的大量URL(每行一个URL)。如果一个人提供代码302我想从文件中删除该行,但我尝试的所有内容都删除了整个文件。我在这里做错了什么?

编辑:粘贴了错误的代码,抱歉!我也有f.write(“”),因为我尝试了不同的删除行的方法,因为我尝试过的所有内容都删除了整个文件。

起初我将它们写入一个新文件,但它花了太长时间(大约20k网址),所以我想从当前文件删除会更快。或者我应该坚持写一个新文件呢?

import urllib2, urllib

class NoRedirectHandler(urllib2.HTTPRedirectHandler):
    def http_error_302(self, req, fp, code, msg, headers):
        infourl = urllib.addinfourl(fp, headers, req.get_full_url())
        infourl.status = code
        infourl.code = code
        return infourl
    http_error_300 = http_error_302
    http_error_301 = http_error_302
    http_error_303 = http_error_302
    http_error_307 = http_error_302

opener = urllib2.build_opener(NoRedirectHandler())
urllib2.install_opener(opener)
opener.addheaders.append(('Cookie', 'birthtime=568022401'))

with open('list.txt', 'w+') as f:
    sites = f.readlines()
    for url in sites:
        try:
            connection = urllib2.urlopen(url)
            position = f.tell()
            if connection.getcode() is 302:
               f.write(" ")
            print "pos:", position
            print connection.getcode()
            connection.close()
        except urllib2.HTTPError, e:
            print e.getcode()

2 个答案:

答案 0 :(得分:0)

您从' list.txt'中读取网站。并且文件处理程序f只具有读权限,没有写权限。 代码:f.write(url)。你想在哪里写?

答案 1 :(得分:0)

您的代码存在一些问题

  1. 离开with部分后,您的文件就会关闭。
  2. 您正在打开文件只是为了阅读
  3. 将整行读入内存是不好的做法。
  4. 你应该:

    1. 用于阅读的开源文件
    2. 打开目标文件以进行写入
    3. 逐行迭代源,如果可以写入目标
    4. 关闭两个文件
    5. 删除源并将目标重命名为原始源名称
    6. 类似的东西:

      with open('list.txt', 'r') as source, open('list-ok.txt', 'w') as target:
        for url in source:
          if do_something(url):
            target.write(url)
      # Rename here "list-ok.txt" to "list.txt"
      
相关问题