简体   繁体   中英

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

Apparently there are other questions about reading the last lines of a .txt file but I really did not understand the answers and don't know how to apply them in my code.

I've created a simple program that writes a sequence of numbers on a .txt file, a new line for each number. Then you can choose how many of them to print.

For some reason, it misses the last 3 lines, for example:

  • I choose to write 100 numbers on the file
  • In the next step, I choose to print n lines.
  • It only prints n-3 lines!

I could "solve" this by adding 3 to the numbers of lines I want to print, but that's just not right. I don't understand why this is happening. There isn't any empty lines on the .txt file. It's literally just a file with one number per line, from beginning to end.

The code is this:

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")

Thanks in advance!

The argument to readline isn't the number of the line , it tells how many characters the readline method is allowed to read at most . Use print(file.readline()) , not print(file.readline(i)) .

Otherwise for input 5 , this will happen: The contents of the file are

1\n2\n3\n4\n5\n

Now, the first iteration reads maximum of 0 characters, returning the empty string '' . This is printed with a newline. The second reads a maximum of 1 characters, which now will contain the digit 0 . This is printed with newline. The third read will read maximum of 2 characters but meets a newline right away, and returns a string that only has one newline. This is printed, with the extra newline from print . Now read 4 will read maximum of 3 characters, and this will now return the string '3\\n' which is just 2 characters. This is printed, with an extra newline. Finally, the last read will read maximum of 4 characters, returns '5\\n' , which again is printed with extra newline.


Finally, no one writes the actual Python code like that. Try the following instead:

# 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!")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM