首页 > 解决方案 > get the last column in every file using open

问题描述

how can i get the last column of an open file. I mean, it isn't the problem to do this with a panda dataframen. I using for this problem the open methode to get only a few needed information out of different txt files. The mean problem is, that the result_metar is in different columns and isn't fixed on column 21.

for xx in range(len(fns_land)):
   with open(fns_land[xx]) as infile:
        for line in infile:
            result_station.append(line.split(',')[0])
            result_date.append(line.split(',')[1])
            result_metar.append(line.split(',')[21])

is there a way to using iloc for example and change the fixed value 21?

The answer i found only show pandas solutions.

Thanks a lot.

Best

标签: pythonpandascsv

解决方案


Here you can return the last column of each open file regardless of the size of your file:

for xx in range(len(fns_land)):
    with open(path) as infile:
         lines = infile.readlines()
         for line in lines:
             result_station.append(line.split(',')[0])
             result_date.append(line.split(',')[1])
             result_metar.append(line.split(',')[-1])

推荐阅读