【发布时间】:2021-11-14 01:54:02
【问题描述】:
words = []
with open("test.txt", "r") as rfile:
n_words = rfile.read().count("*")
for n in range(0, n_words):
words.append(input("Type word: "))
for line in rfile.readlines():
ind = [x for x, ch in enumerate(line) if ch == "*"]
if ind:
print(ind)
当我运行这段代码时,我得到了这个: 输入词:asd 输入词:asd 输入词:asd 输入词:asd 输入词:悲伤 输入词:asd 输入单词:asd
程序不运行第二个 for 循环。 无论我先放哪个 for 循环,第二个都没有运行。 有谁知道为什么?
【问题讨论】:
-
我猜是因为
read()已经消耗了整个文件,所以readlines()没有任何东西可以处理。 -
"rfile" 已经完全是 "read()",因此 "readlines()" 不再读取(按交换顺序相同)。您必须将文件指针设置为以“seek”方法开头。
标签: python for-loop file-handling