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

时间:2014-10-16 10:15:35

标签: python string file-io web-scraping

我在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

1 个答案:

答案 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)