Reputation: 163
I am approached with a problem of organizing an input file into a dictionary and for my algorithm I have decided to firstly turn an input file into a list of each lines (str). Basically, given:
ABCDE
FGHIJ ABCDEFG
FGHIJ ABCDEFG LOLOA
It will turn into
[['ABCDE'], ['FGHIJ', 'ABCDEFG'], ['FGHIJ', 'ABCDEFG', 'LOLOA']]
I am unsure how I can start.
Upvotes: 0
Views: 76
Reputation: 9008
fname = "*.txt"
f = open(fname,'r')
lines = f.readlines()
open means to open the file, and 'r' option means to read it (other option includes 'w' to write)
Upvotes: 0
Reputation:
You need to do two things:
Read in the file. This is best accomplished with a with-statement.
Use a list comprehension or similar device to split the lines on whitespace.
Below is a demonstration:
>>> with open('/path/to/file.txt') as myfile:
... print [line.split() for line in myfile]
...
[['ABCDE'], ['FGHIJ', 'ABCDEFG'], ['FGHIJ', 'ABCDEFG', 'LOLOA']]
>>>
Upvotes: 4