2014-10-16 55 views
0

我正在Python中編寫一個網頁抓取腳本,它從文本文件的第一行拉出一個'ID'並將其附加到部分URL ;然後從所述URL下載圖像。一切工作正常,但是當我使用第三個函數(它包含下載的實際代碼 - 它工作正常)運行它時,它不會通過刪除第一行來更新文本文件。Python不會重寫第一行使用readlines()和for循環的文件

我敢肯定,我在這裏失蹤的東西,任何幫助將不勝感激。

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

如何'unused_id'(整個第一行)永遠等於'first_line'(第一行,沒有前三個字符,'strip'ped)?爲什麼不僅僅是爲了排隊[1:]:'? – jonrsharpe 2014-10-16 10:19:23

+0

當你說'對於行[1:]:'這行會做與'[3:]'相同的事情嗎? – 2014-10-16 10:24:41

+0

看起來像你的問題是你在'delete_used_id'中的條件。你讀第一行'[3:]',然後檢查'unused_id'。從邏輯上講,它與檢查「foobar」[3:] ==「foobar」是否相似,第一個只是「bar」。 – nerdwaller 2014-10-16 10:25:34

回答

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) 
+0

你不需要'if line!= first_line:',因爲'lines [1:]'是除第一行之外的所有行的列表。 – 2014-10-16 10:32:24

+0

謝謝@PM 2Ring,現在會重構這個:) – 2014-10-16 10:34:55