Python read text file columnwise

Piet van Oostrum piet-l at vanoostrum.org
Fri Jan 11 19:03:56 EST 2019


shibashibani at gmail.com writes:

> Hello
>> 
>> I'm very new in python. I have a file in the format:
>> 
>> 2018-05-31	16:00:00	28.90	81.77	4.3
>> 2018-05-31	20:32:00	28.17	84.89	4.1
>> 2018-06-20	04:09:00	27.36	88.01	4.8
>> 2018-06-20	04:15:00	27.31	87.09	4.7
>> 2018-06-28	04.07:00	27.87	84.91	5.0
>> 2018-06-29	00.42:00	32.20	104.61	4.8
>
> I would like to read this file in python column-wise.  
>
> I tried this way but not working ....
>   event_list = open('seismicity_R023E.txt',"r")
>     info_event = read(event_list,'%s %s %f %f %f %f\n');

Why would you think that this would work?

See https://docs.python.org/3/library/csv.html

Something like:

#!/usr/bin/env python3

import csv

with open('testcsv.csv', newline='') as csvfile:
    reader = csv.reader(csvfile, delimiter='\t')
    for row in reader:
        for i in range(2, 5):
            row[i] = float(row[i])
        print(row)

You could convert the first two columns to datetime format if you wish.
-- 
Piet van Oostrum <piet-l at vanoostrum.org>
WWW: http://piet.vanoostrum.org/
PGP key: [8DAE142BE17999C4]



More information about the Python-list mailing list