Python 迴圈不適用於 readlines()
它應該可以計算「----------------------- --」行的數量,但它不起作用,也可以用print(" test") 不會在控制台中顯示,它總是返回0。但例如行 print("hi") 可以工作。程式就是看不到我的循環,我不知道為什麼。 :(
def check_id(): with open('data.txt', 'r') as f: lines = f.readlines() ad = 0 print("hi") # this line works for i in lines: print("test") # this line doesn't work if i == "-------------------------": ad += 1 return str(ad)
如果我需要發送完整程式碼來解決問題,請詢問
我將模式“a ”更改為“r”,以便它可以正確讀取行,確實如此,但我仍然無法檢查數組以獲取該行的數量。如果您有任何猜測或解決方案,請寫下來。
編輯:這是我的 data.py 和檔案 data.txt 中的文字的完整程式碼
from datetime import date date = date.today() def write_note(line): with open('data.txt', 'a') as f: if line == "!quit": f.write('\n') f.write("-------------------------") f.write('\n') ad = check_id() f.write(ad) f.write('\n') f.write("________________________") f.write('\n') else: f.write(line) f.write("\n") def read_note(id): with open('data.txt', 'r') as f: pass def see_all(): with open('data.txt', 'r') as f: get_lines = f.readlines() for i in get_lines: print(i) return get_lines def del_note(ad): with open('data.txt', 'a') as f: pass def logs(): pass def check_id(): with open('data.txt', 'r') as f: ad = 0 for i in f: if i == "-------------------------": ad += 1 return str(ad)
現在是 txt 檔:
fugy hello hai bebra ------------------------- 0 ________________________ uha imna fsjfoe geso;rsevdn ------------------------- 0 # This one ________________________
我正在嘗試製作筆記本,以便可以寫筆記並閱讀它們。刪除 func 我稍後會做。想法是每次添加註釋時使這個零更大。
正確答案
我認為問題出在您的data.txt
檔案(可能是空的,因為您提到 "test"
在控制台中不可見,這表示該腳本不在for
循環中運行,在其他word: lines
迭代器的長度為零)。
我已經編寫了一個工作程式碼,您可以在下面看到程式碼和帶有腳本輸出的測試檔案。
程式碼:
def check_id(): with open('data.txt', 'r') as opened_file: ad = 0 print("hi") # this line works for i in opened_file: print("test") # this line doesn't work if i == "-------------------------": ad += 1 return str(ad) result = check_id() print(f"result: {result}")
data.txt
的內容:
test_1 ------------------------- test_2 ------------------------- test_3 ------------------------- test_4
測試:
> python3 test.py hi test test test test test test test result: 0
編輯:
op分享了完整的原始程式碼和使用的data.txt
,其中包含cr
lf
字元(有關該字元的詳細信息)。這意味著必須使用 rstrip
方法對這些行進行條紋。
在這種情況下,只有 check_id
函數相關,因此我隻共享修改後的函數:
def check_id(): with open('data.txt', 'r') as f: ad = 0 for i in f: # The cr and lf characters should be removed from line. Please see the above reference for details. if i.rstrip() == "-------------------------": ad += 1 return str(ad) result = check_id() print(result). # Result is 4
以上是Python 迴圈不適用於 readlines()的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)