Python:循环读取文件中的特定行
我有一个文件,里面有一些行,我想提取每行的第三列;不过文件里没有数字列:
- 红色;蓝色;绿色;白色;橙色;
- 绿色;白色;橙色;
- 蓝色;绿色;白色;
- 红色;蓝色;绿色;白色;
- 蓝色;绿色;白色;橙色;
- 橙色
- 绿色;白色;橙色;
- 白色;橙色
- 绿色;
我用这行代码来实现这个:
lines = i.split(";")[2]
问题是,有些行只有一列或两列,这样就会出现“索引超出范围”的错误。请问我该怎么解决这个问题呢?
非常感谢!
4 个回答
2
简单的解决办法就是检查一下每行有多少列,然后忽略那些列数少于三列的行。
third_columns = []
with open("...") as infile:
for line in infile:
columns = line.split(';')
if len(columns) >= 3:
third_columns.append(columns[2])
如果你在处理CSV文件(看起来你是在做这个),那么最好使用现成的CSV解析工具,比如标准库里的那个。
2
像这样怎么样:
cols = i.split(";")
if (len(cols) >= 3):
lines = cols[2]
else:
#whatever you want here
1
用切片来代替索引。
>>> with open('test.txt') as f_in:
... column3 = (line.split(';')[2:3] for line in f_in)
... column3 = [item[0] for item in column3 if item]
...
>>> column3
[' Green', ' Orange', ' White', ' Green', ' White', ' Orange']