user3225528
user3225528

Reputation: 163

Convert an input file into a list of each line

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

Answers (2)

Yilun Zhang
Yilun Zhang

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

user2555451
user2555451

Reputation:

You need to do two things:

  1. Read in the file. This is best accomplished with a with-statement.

  2. 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

Related Questions