簡體   English   中英

我正在嘗試使用for循環打印.txt文件的多行。 總是缺少最后三行

[英]I'm trying to print a number of lines of a .txt file using a for loop. It's always missing the last three lines

顯然,還有其他有關讀取.txt文件最后幾行的問題,但是我真的不明白答案,也不知道如何在我的代碼中應用它們。

我創建了一個簡單的程序,在.txt文件中寫了一個數字序列,每個數字都換了一行。 然后,您可以選擇要打印的數量。

由於某種原因,它錯過了最后三行,例如:

  • 我選擇在文件上寫100個數字
  • 在下一步中,我選擇打印n行。
  • 它只打印n-3行!

我可以通過在要打印的行數上加3來“解決”這一問題,但這是不對的。 我不明白為什么會這樣。 .txt文件上沒有任何空行。 從字面上看,它只是一個從頭到尾每行只有一個編號的文件。

代碼是這樣的:

print("How many numbers to write on file?")
x = input()
x = int(x)

file = open("bla.txt", "w")

for i in range(0,x):
    file.write(str(i))
    file.write("\n")

file.close()

print("How many numbers to print?")

y = input()
y = int(y)

file = open("bla.txt", "r")

for j in range(0,y):
    print(file.readline(j))

file.close()

print("Done!\n")

提前致謝!

readline的參數不是行號 ,它告訴readline方法最多允許讀取多少個字符 使用print(file.readline()) ,而不是print(file.readline(i))

否則對於輸入5 ,將發生以下情況:文件的內容為

1\n2\n3\n4\n5\n

現在,第一次迭代最多讀取0個字符,並返回空字符串'' 這是用換行符打印的。 第二個讀取最多1個字符,現在將包含數字0 這是用換行符打印的。 第三次讀取最多讀取2個字符,但立即遇到換行符,並返回僅包含一個換行符的字符串。 這是已打印的,帶有來自print的多余的換行符。 現在讀取4將最多讀取3個字符,這將返回字符串'3\\n' ,這只是2個字符。 打印出來,並帶有額外的換行符。 最后,最后一次讀取將最多讀取4個字符,並返回'5\\n' ,並再次打印出額外的換行符。


最后,沒有人會像這樣編寫實際的Python代碼。 請嘗試以下操作:

# you can add a prompt to the input itself
num_lines = int(input("How many numbers to write on file? "))

# with will automatically close the file upon exit from the block
with open("bla.txt", "w") as output_file:
    # 0 as start implied
    for i in range(num_lines):
        # print will format the number as a string, a newline is added automatically
        print(i, file=output_file)

num_lines = int(input("How many lines to read? "))    
with open("bla.txt", "r") as input_file:
    # _ is the common name for a throw-away variable 
    for _ in range(num_lines):
        # get the *next* line from file, print it without another newline
        print(next(input_file), end='')

# or to read *all* lines, use
# for line in file:
#     print(line)    

print("Done!")

暫無
暫無

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

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