简体   繁体   中英

Print certain number of lines from file

I have an assignment that involves reading and printing lines from files. I am on a problem right now where I have to print the first n amount of lines from the file.

I have a for-loop setup that I thought would do this for me, but it is giving me a ValueError . I may just not understand how the for-loop works in Python. I am used to Java and C++ programming.

This is the loop I have set up that I thought would give me the number of lines I want from the file.

for i, line in open_file:
    if i > desired_number_of_lines:
        break
    print(line)

Does the i variable not act as a counter in this case that just counts from 0? This is the error I am receiving when running the program.

ValueError: too many values to unpack (expected 2)

Try this and it might work:

with open("test.txt", "r") as test:
    text_file = test.readlines()
desired_number_of_lines = 5

for n in range(len(text_file) - 1):
    if n < desired_number_of_lines:
        print(text_file[n])

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