Python-在多个for循环之间未检测到txt文件

问题描述 投票:0回答:1

我遇到了一个错误,即我打开的'.txt'文件不会被多个循环检测到。

hand = open('filter_test.txt')   # Open 1

# Loop 1
for line in hand:
    line = line.rstrip()
    if re.search(r'^X.*:', line):
        print(line)


# I can still see 'hand' here.
print(hand)

# If 'Open 2' is not there, the 'Loop 2' will not pick up 'filter_test.txt'

hand = open('filter_test.txt')    # Open 2

#Loop 2   
for line in hand:
    # If 'Open 2' is not present, line will not print anything here.
    print(line)
    line = line.rstrip()
    if re.search(r'^X-\S+:', line):
        print(line)

我仍然可以在“循环1”和“循环2”之间看到“手”,但是如果我没有“打开2”,则“循环2”将不会拾取它。

知道为什么会这样吗?不得不为我要运行的每个循环重新打开文件似乎很愚蠢]

欢呼声

python python-3.x loops
1个回答
2
投票

您可以尝试

hand = open('filter_test.txt')  
hand_content = hand.read()
hand.close()

for line in hand_content:
    line = line.rstrip()
    if re.search(r'^X.*:', line):
        print(line)

print(hand_content)

for line in hand_content:
    print(line)
    line = line.rstrip()
    if re.search(r'^X-\S+:', line):
        print(line)

问题是您尝试打开一个文件,而您没有关闭克服方法,因为将文件内容存储在变量中并将该变量用于循环。

© www.soinside.com 2019 - 2024. All rights reserved.