简体   繁体   English

Python将不会使用readlines()和for循环删除第一行来重写文件

[英]Python won't rewrite file with first line removed using readlines() and for loop

I' writing a web scraping script in Python that pulls an 'ID' from the first line of a text file and appends it to a partial URL; 我正在用Python编写一个网络抓取脚本,该脚本从文本文件的第一行中提取“ ID”并将其附加到部分URL; then downloads an image from said URL. 然后从所述网址下载图片。 Everything works fine, but when I run it using the third function (which contains the actual code for downloading - this works fine) it doesn't update the text file by deleting the first line. 一切正常,但是当我使用第三个函数(包含用于下载的实际代码-可以正常运行)运行它时,不会通过删除第一行来更新文本文件。

I'm sure there is something I am missing here, and any help would be greatly appreciated. 我敢肯定,这里我缺少什么,任何帮助将不胜感激。

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

Thanks to jonrsharpe and nerdwaller: 感谢jonrsharpe和nerdwaller:

ANSWER: 回答:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM