Python read text file columnwise
About the original question: If I were you, I would put the 3 numbers into a list (or a tuple, if you don't need to modify them) and put this into a dictionary. The key would be the date & time string.
Then, if you need to find a particular entry you can look it up by date and time. But I suspect, since you want column access, you won't need to do that. You can iterate through the entries in the dictionary easily and extract the data from a column, or from all the columns, if that?s what you want.
for entry in mydict:
value = entry.datalist # I hope I have the syntax correct
Now, what you do with value is up to you. I think personally rather than building a list I would make a generator function. A generator uses a "yield" statement to return a value, and it waits in that state. The next time you call it it continues and returns the next value. Kind of useful when the alternative is making and passing around huge lists.
--- Joseph S.
From: DL Neil <PythonList at DancesWithMice.info>
Sent: Saturday, January 12, 2019 4:48 PM
To: python-list at python.org
Subject: Re: Python read text file columnwise
On 12/01/19 1:03 PM, Piet van Oostrum wrote:
> shibashibani at gmail.com writes:
>>> 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');
To the OP:
Python's standard I/O is based around data "streams". Whilst there is a concept of "lines" and thus an end-of-line character, there is not the idea of a record, in the sense of fixed-length fields and thus a defining and distinction between data items based upon position.
Accordingly, whilst the formatting specification of strings and floats might work for output, there is no equivalent for accepting input data.
Please re-read refs on file, read, readline, etc.
> Why would you think that this would work?
To the PO:
Because in languages/libraries built around fixed-length files this is
how one specifies the composition of fields making up a record - a data
structure which dates back to FORTRAN and Assembler on mainframes and
other magtape-era machines.
Whilst fixed-length records/files are, by definition, less flexible than
the more free-form data input Python accepts, they are more efficient
and faster in situations where the data (format) is entirely consistent
- such as the OP is describing!