为什么我的代码删除整个文本文件而不是行?
Why does my code delete entire text file instead of line?
我正在检查一大堆 URL(每行一个 URL)的 http 代码。如果有人给出代码 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()
您阅读了来自 'list.txt' 的网站。而文件处理程序f只有读权限,没有写权限。
代码:f.write(url)。你想写在哪里?
您的代码几乎没有问题
- 一旦您离开
with
部分,您的文件就会关闭。
- 您打开文件只是为了阅读
- 将整行读入内存是不好的做法。
你应该:
- 打开源文件以供阅读
- 打开目标文件进行写入
- 逐行遍历源代码,如果成功则写入目标
- 关闭两个文件
- 删除源并将目标重命名为原始源名称
类似于:
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"
我正在检查一大堆 URL(每行一个 URL)的 http 代码。如果有人给出代码 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()
您阅读了来自 'list.txt' 的网站。而文件处理程序f只有读权限,没有写权限。 代码:f.write(url)。你想写在哪里?
您的代码几乎没有问题
- 一旦您离开
with
部分,您的文件就会关闭。 - 您打开文件只是为了阅读
- 将整行读入内存是不好的做法。
你应该:
- 打开源文件以供阅读
- 打开目标文件进行写入
- 逐行遍历源代码,如果成功则写入目标
- 关闭两个文件
- 删除源并将目标重命名为原始源名称
类似于:
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"