python - 从文本文件读取行后python代码中的IndexError

标签 python python-3.x

有人能告诉我这段 python 代码出了什么问题吗?它看起来很傻,因为代码非常简单,但我是编码的初学者,希望可以理解。

f = open("countries.txt", "r")

countries = []

for line in f:
    line = line.strip()
    countries.append(line)

f.close()

print(countries)
print(len(countries))

for country in countries:
    if country[0] == "T":
        print(country)

我不断收到以下错误:

 line 16, in <module>
    if country[0] == "T":
IndexError: string index out of range

最佳答案

if country[0] == "T": 如果 country 的长度为零,将会崩溃。如果您的文件包含一个完全空白的行,则可能会发生这种情况。

尝试在附加到 countries 时过滤掉空行:

for line in f:
    line = line.strip()
    if line:
        countries.append(line)

关于python - 从文本文件读取行后python代码中的IndexError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43231809/

相关文章:

python - 将 python 脚本打包到 grunt 插件中

Python在网页弹出窗口中从电脑中选择图像

python - 在 QuerySet 值列表中获取 ChoiceField 的完整标签名称

python - 如何从 .csv 文件加载数据而不导入 .csv 模块/库

通过 numpy 数组进行复杂数学计算累积和的 Pythonic 方法

Python - 不同的打印方式?

python - 如何从Python中的任意行开始使用read next()?

python - Cython 如何将 char** 转换为 const char**?

python-3.x - 使用 python 抓取网站搜索栏

python-3.x - 禁用部分 nlp 管道