簡體   English   中英

Python 3.2 - readline() 正在跳過源文件中的行

[英]Python 3.2 - readline() is skipping lines in source file

我有一個用多行創建的 .txt 文件。

當我使用計數累加器運行 for 循環時,它會跳過行。

它跳過第一行,從第二行開始,打印第四行,第六行,等等......

我錯過了什么?

** for your reading pleasure**
def main():
    # Open file line_numbers.txt
    data_file = open('line_numbers.txt', 'r')

    # initialize accumulatior
    count = 1


    # Read all lines in data_file
    for line in data_file:
        # Get the data from the file
        line = data_file.readline()

        # Display data retrieved
        print(count, ": ", line)

        # add to count sequence
        count += 1

嘗試完全刪除“line=data_file.readline()”? 我懷疑“for line in data_file:”也是一個 readline 操作。

您的 for 循環正在遍歷 data_file 並且您的 readline() 正在與之競爭。 為此結果擦除代碼的line = data_file.readline()行:

# Read all lines in data_file
count = 1
for line in data_file:
    # Display data retrieved
    print(count, ": ", line)

    # add to count sequence
    count += 1

for line in data_file已經為您獲取了每一行的文本 - 隨后對 readline 的調用將獲取以下行。 換句話說,刪除對 readline 的調用將做你想做的事。 同時,您不需要自己跟蹤累加器變量 - python 有一種使用enumerate的內置方法 - 換句話說:

data_file = open('line_numbers.txt', 'r')
for count, line in enumerate(data_file):
    ...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM