简体   繁体   中英

Segment a txt file column to lists

I am have text file with multiple columns and separated by commas.

I am trying to read it and put each column into it's own separate list but I can't seem to do it.

What I've done so far:

with open(file, 'r') as file_test:
    file_lines = file_test.readlines()
    file_strip = [line.strip("\n") for line in file_lines]

#I've split big list into separate lists within `file_strip`
    file_columns= [file_strip [i:i + 1] for i in range(0, len(file_strip ), 1)][2:]

So now my data is as follows:

[['22AUG18 000000, 22AUG18 000149, 5.722, UOS2'], ['22JUL18 012703, 22JUL18 013810, 52.2811, UOS2']]

I don't know how to get rid of the ' in the beginning and end of each list too

I want the first element in each list to be in List1 , 2nd element in each list to be in List2 etc...

Why not use the csv module? It was designed to do what you want to do!

import csv

with open(file, 'r') as file_test:
    csv_test = csv.reader(file_test)
    for row in csv_test:
         print(row)

Will print

['22AUG18 000000', '22AUG18 000149', '5.722', 'UOS2']
['22JUL18 012703', '22JUL18 013810', '52.2811', 'UOS2']

If you want to separate that in lists you can zip() it:

with open(file, 'r') as file_test:
    csv_test = csv.reader(file_test)
    list1, list2, list3, list4 = zip(*csv_test)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM