目錄
正確答案
首頁 後端開發 Python教學 Python 迴圈不適用於 readlines()

Python 迴圈不適用於 readlines()

Feb 06, 2024 am 09:54 AM

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中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

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

AI Clothes Remover

AI Clothes Remover

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

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
2 週前 By 尊渡假赌尊渡假赌尊渡假赌
倉庫:如何復興隊友
4 週前 By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

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

如何使用Python查找文本文件的ZIPF分佈 如何使用Python查找文本文件的ZIPF分佈 Mar 05, 2025 am 09:58 AM

如何使用Python查找文本文件的ZIPF分佈

如何在Python中下載文件 如何在Python中下載文件 Mar 01, 2025 am 10:03 AM

如何在Python中下載文件

我如何使用美麗的湯來解析HTML? 我如何使用美麗的湯來解析HTML? Mar 10, 2025 pm 06:54 PM

我如何使用美麗的湯來解析HTML?

python中的圖像過濾 python中的圖像過濾 Mar 03, 2025 am 09:44 AM

python中的圖像過濾

如何使用Python使用PDF文檔 如何使用Python使用PDF文檔 Mar 02, 2025 am 09:54 AM

如何使用Python使用PDF文檔

如何在django應用程序中使用redis緩存 如何在django應用程序中使用redis緩存 Mar 02, 2025 am 10:10 AM

如何在django應用程序中使用redis緩存

引入自然語言工具包(NLTK) 引入自然語言工具包(NLTK) Mar 01, 2025 am 10:05 AM

引入自然語言工具包(NLTK)

如何使用TensorFlow或Pytorch進行深度學習? 如何使用TensorFlow或Pytorch進行深度學習? Mar 10, 2025 pm 06:52 PM

如何使用TensorFlow或Pytorch進行深度學習?

See all articles