Hi! On 15/01/2019 17:04, Neil Cerutti wrote: > On 2019-01-11, shibashib...@gmail.com <shibashib...@gmail.com> wrote: >> 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'); > > If it's really tabular data in fixed-width columns you can read > it that way with Python. > > records = [] > for line in file: > record = [] > i = 0 > for width in (30, 8, 7, 5): # approximations > item = line[i:i+width] > record.append(item) > i += width > records.append(record) > > This leaves them all strings, which in my experience is more > convenient in practice. You can convert as you go if you > want,though it won't look nice and simple any longer. >
Perhaps even better approach is to use csv module from standard library: import csv csv_reader = csv.reader(file, dialect="excel-tab") for row in csv_reader: # do something with record data which is conveniently parsed to list print(row) ['2018-05-31', '16:00:00', '28.90', '81.77', '4.3'] ... ['2018-06-29', '00.42:00', '32.20', '104.61', '4.8'] BR, Juris -- https://mail.python.org/mailman/listinfo/python-list