Benualdas Questioneer
Benualdas Questioneer

Reputation: 35

How to make a list from a text file

Let's say I have a text file:

one #first column
two

three four #second column, same text file
 five
six

Now how would you make a list like this using that text file:

['one', 'two'] #first column list
['three', 'four', 'five', 'six'] #second column list from the same text file

I suppose this can be done by using split() or splitlines()?

Upvotes: 0

Views: 1042

Answers (2)

Quantum Sushi
Quantum Sushi

Reputation: 514

Use a character to separate your columns on every line, like ";". Then, consider here an exemple of a file with 5 lines :

file = open("foo.txt", "rw+")
line = file.readlines()
print("Read Line: %s" % (line))

line = file.readlines(2)
print("Read Line: %s" % (line))
# Close opened file
file.close()

You can learn more about it, this is a very simple thing called "readlines". So just search for documentation... Then you can use the split command, with the syntax :

x = yourstring.split(separator, maxsplit)

x is now a list of strings. Just ignore maxsplit, your separator is here in my case ";". So you got your strings with your lines that you will split into columns : use split to get then a list of list of strings. You're still here ? XD

Then, I won't show you the full code, that's too easy. You got all the tools you need to do this, and obtain a list with many lists inside, your lines. Into these lists, you got strings, your columns. Then, little hint, use a for i in range(len(won't say you what)) to append to a column 1 list element n°1, to a column 2 list, element n°2, etc... To sort your strings into lists, to get a bit order into this mess !

Ask me if you got any questions, hope I've been clear ;D

The Machinist

Upvotes: 1

kederrac
kederrac

Reputation: 17322

you can use:

import re

with open('my_file.txt') as fp:
    l = fp.read()

col = l.split('\n\n')
columns = [c.split()  for c in col]
columns

output:

[['one', 'two'], ['three', 'four', 'five', 'six']]

you can access the columns by index, for the first column you can use:

columns[0]

output:

['one', 'two']

Upvotes: 4

Related Questions