读取文件、if语句和break

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

我需要的是读取一个简单的文本文件,并在某个字符串匹配时停止读取。文本文件是:

  • 苹果
  • 香蕉
  • 西瓜
  • 梨子
  • 杏子

我的最小“工作”示例

    with open("C:\\Python\\test.txt") as file:
        while line := file.readline():
            print(line.rstrip())
            if line.rstrip() == "Pear":
                break

这会返回错误消息

TabError:缩进中制表符和空格的使用不一致

你能帮我吗?

python
1个回答
0
投票

在 Python 中,空格和制表符是代码的一部分。

当您在同一代码块中混合使用制表符和空格进行缩进时,Python 中的

"TabError: inconsistent use of tabs and spaces in indentation"
就会发生。

Python 要求一致使用制表符或空格来缩进 for、if 等函数

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