如何打印文件中特定长度的行(Python)

bw6*_*293 1 python file

我是Python新手。我有一份文档,每行有一个随机单词。这个文件有几千个字。我试图只打印四个字母长的单词。我试过这个:

f=open("filename.txt")
Words=f.readlines()
for line in f:
    if len(line)==4:
        print(line)
f.close()
Run Code Online (Sandbox Code Playgroud)

但是当我这样做时,python 是空白的。我假设我也需要去掉空格,但是当我这样做时

f.strip()
Run Code Online (Sandbox Code Playgroud)

我收到一条错误,指出 .strip() 不适用于列表项。任何帮助都是感激不尽。谢谢!

Ale*_*ton 5

“Python 为空”,因为您尝试第二次迭代该文件。

第一次是使用readlines(),因此当迭代完成时,您位于文件末尾。然后,当您执行此操作时,for line in f您已经位于文件末尾,因此没有剩余内容可供迭代。要解决此问题,请挂断对 的呼叫readlines()

为了做你想做的事,我会这样做:

with open('filename.txt') as f:
    for line in f:  # No need for `readlines()`
        word = line.strip()  # Strip the line, not the file object.
        if len(word) == 4:
            print(word)
Run Code Online (Sandbox Code Playgroud)

您的另一个错误发生的原因f.strip()是因为它f是一个文件对象,但您只有strip一个字符串。因此,只需在每次迭代中拆分line,如上例所示。