简体   繁体   English

为什么我的文件关闭?

[英]Why does my file close?

For some reason my file seems unable to be accessed after i invoke readlines() Any idea why? 由于某种原因,在我调用readlines()之后,似乎无法访问我的文件。为什么?

The main concern is that the for-loop after doesn't work. 主要问题是for循环之后不起作用。 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. fHand.readlines()读取整个文件,因此您的文件指针位于文件的末尾。

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. 如果您确实想这样做(提示:您可能不需要),则可以在for循环之前添加fHand.seek(0) ,以将指针移回文件的开头。

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. 通常,当您在Python中查看文件时, .read*命令不是您想要的。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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