它应该计算“-------------------------”行的数量,但它不起作用,也与 print("test" 行) 不会在控制台中显示,并且始终返回 0。但是例如行 print("hi") 可以工作。程序就是看不到我的循环,我不知道为什么。 :(
def check_id():
with open('data.txt', 'r') as f:
lines = f.readlines()
ad = 0
print("hi") # This line works
for i in lines:
print("test") # This line doesn't work
if i == "-------------------------":
ad += 1
return str(ad)
如果我需要发送完整代码来解决问题,请询问
我将模式“a+”更改为“r”,以便它可以正确读取行,确实如此,但我仍然无法检查数组以获取该行的数量。如果您有任何猜测或解决方案,请写下来。
我认为问题在于您的
data.txt
文件(可能它是空的,因为您提到 "test"
在控制台中不可见,这意味着脚本不在 for
循环中运行,换句话说: lines
迭代器的长度为零)。
我已经编写了一个工作代码,您可以在下面看到代码和带有脚本输出的测试文件。
代码:
def check_id():
with open('data.txt', 'r') as opened_file:
ad = 0
print("hi") # This line works
for i in opened_file:
print("test") # This line doesn't work
if i == "-------------------------":
ad += 1
return str(ad)
result = check_id()
print(f"Result: {result}")
data.txt
的内容:
test_1
-------------------------
test_2
-------------------------
test_3
-------------------------
test_4
测试:
> python3 test.py
hi
test
test
test
test
test
test
test
Result: 0