我在Python中编写了一个Web抓取脚本,它从文本文件的第一行中提取“ID”并将其附加到部分URL;然后从所述URL下载图像。一切正常,但当我使用第三个函数(包含实际的下载代码 - 运行正常)运行它时,它不会通过删除第一行来更新文本文件。
我确信我在这里缺少一些东西,任何帮助都将不胜感激。
def delete_used_id():
# open and save all ids
id_file_r = open('C:/Users/my.name/Documents/IDs.txt', 'r')
lines = id_file_r.readlines()
first_line_unf = str(lines[0])[3:]
first_line = first_line_unf.strip()
id_file_r.close()
# reopen in write mode
id_file_w = open('C:/Users/my.name/Documents/IDs.txt','w')
for unused_id in lines:
if unused_id != first_line:
id_file_w.write(unused_id)
id_file_w.close()
print("Deleting used ID: " + first_line)
def get_id_from_file():
id_file = open('C:/Users/my.name/Documents/IDs.txt', 'r')
# slice the first 3 chars off of the string
farmer_id_unf = id_file.readline()[3:]
farmer_id = farmer_id_unf.strip()
print("Getting Farmer ID: " + farmer_id)
return farmer_id
答案 0 :(得分:0)
感谢jonrsharpe和nerdwaller:
<强>解答:强>
def delete_used_id():
# open and save all ids
id_file_r = open('C:/Users/my.name/Documents/IDs.txt', 'r')
lines = id_file_r.readlines()
first_line_unf = lines[0][3:]
first_line = first_line_unf.strip()
id_file_r.close()
# reopen in write mode
id_file_w = open('C:/Users/my.name/Documents/IDs.txt','w')
for line in lines[1:]:
id_file_w.write(line)
id_file_w.close()
print("Deleting used ID: " + first_line)