Sukanta
Sukanta

Reputation: 103

Reading a txt file into a list in python

I just started to learn python and I was wondering how to read a bunch of numbers from a txt file and put it into a sort of list. The txt file I want to read has three numbers next to each other with a space in between.

Like this:

24 39 45\n

I want to read this file into a list: [24, 39, 45]

How can I do that? The .readlines() method doesn't seem to work as it turns the whole line into one single element: list[0] = ['24 39 45\n'].

Pardon me if this sounds like a stupid question. This is my first question here. Thank you!

Upvotes: 2

Views: 2464

Answers (3)

Margouma Saleh
Margouma Saleh

Reputation: 23

try the code follows

g = open("demofile.txt", 'r')
step1=g.readlines()
step2=[]
for a in step1:
    step2.append(a.split())
print(step2)

Upvotes: 0

Chase
Chase

Reputation: 5615

You should use .read().splitlines() to first get a list where each element looks like ['24 39 45'] then, a .map with a .split to split each of those by space.

with open(filename, 'r') as textfile:
    content = textfile.read().splitlines()
content = list(map(lambda x: x.split(' '), content))

Output-

[['24', '39', '45'], ['52', '42', '39']]

Where textfile was-

24 39 45

52 42 39

This will return a list of lists, where each element will be a list of numbers

Upvotes: 2

Dejke
Dejke

Reputation: 168

.readLine().split()

It reads the full line, and uses split to separate it into space-separated values.

Upvotes: 1

Related Questions