[英]Python iterate through file and extract specific lines to a list for SQL injection
[英]Python: loop through a file for specific lines
我要在第三列中的文件中有以下几行: 在文件中,我没有数字列:
我使用以下代码行来做到这一点:
lines = i.split(";")[2]
问题是某些行只有一两列,所以它给我“索引超出范围”错误。 请告诉我如何解决这个问题?
非常感谢Adia
那这样的事情呢:
cols = i.split(";")
if (len(cols) >= 3):
lines = cols[2]
else:
#whatever you want here
简单的解决方案是检查列数,并忽略少于三列的行。
third_columns = []
with open("...") as infile:
for line in infile:
columns = line.split(';')
if len(columns) >= 3:
third_columns.append(columns[2])
而且,如果您解析CSV(似乎与您一样),则最好使用众多现有CSV解析器之一, 例如,标准库中的之一 。
使用切片而不是索引。
>>> 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']
for line in open("file"):
try:
s=line.split(";")[2]
except: pass
else:
print s
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.