Skip to main content
 首页 » 编程设计

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

2025年05月04日15duanxz

有人能告诉我这段 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)