简体   繁体   中英

Why does my file close?

For some reason my file seems unable to be accessed after i invoke readlines() Any idea why?

The main concern is that the for-loop after doesn't work. It doesn't iterate through the lines.

with open('wordlist.txt') as fHand:
    content = fHand.readlines()

    lines = 0

    for _ in fHand:
        lines += 1

fHand.readlines() reads the whole file, so your file pointer is at the end of the file.

If you really want to do this (hint: you probably don't) you can add fHand.seek(0) before the for loop to move the pointer back to the beginning of the file.

with open('wordlist.txt') as fHand:
    content = fHand.readlines()
    fHand.seek(0)

    lines = 0
    for _ in fHand:
        lines += 1

In general, the .read* commands are not what you're looking for when you're looking at files in Python. In your case you should probably do something like:

words = set()  # I'm guessing

with open("wordlist.txt") as fHand:
    linecount = 0
    for line in fHand:
        # process line during the for loop
        # because honestly, you're going to have to do this anyway!
        # chances are you're stripping it and adding it to a `words` set? so...
        words.add(line.strip()
        linecount += 1

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