user14655550
user14655550

Reputation:

Converting the text file into a string or list

I have the following data in my text file:

5*0 4 3 2 5 7 7 3 6 3 2 6

8*2 4 5 6 7 8 7 3 7 7 3

I want to work on the data in python. so, I guessed it is better to convert it to string or list.

I used the following code:

a = open('test.txt', 'r')
b = a.readlines()
c = [x.replace('\n','') for x in b]
print(c)

but it gives:

['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']

I wondered to know how I can convert it to the following:

['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

Upvotes: 0

Views: 3144

Answers (5)

RogueManiac
RogueManiac

Reputation: 1

 with open('test.txt') as file: 
        print(file.read().split())

I used the with method to open and read the file along with the .read() method which reads the whole file instead of one line at a time, then the .split() method splits string at each ' ', returning a list.

Upvotes: 0

coderoftheday
coderoftheday

Reputation: 2075

I will convert this to list compression and edit the post, but here it is without

a = open('test.txt', 'r')
b = a.readlines()
c = [a for n in str(b).split('\n') for a in n.split(' ') if a != '']
print(c)

>>> ['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

Upvotes: 0

Arturo Mendoza
Arturo Mendoza

Reputation: 114

I would simply change the readlines by the read method (does not split the lines into different list items), then change the '\n' newline character by spaces and finally split the string by spaces.

a = open('test.txt', 'r')
b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
a.close()
print(c)

I would suggest to use the with statement so as to not forget to close the file

with open('test.txt', 'r') as a:
    b = a.read()
c = b.replace('\n', ' ').strip().split(' ')
print(c)

Upvotes: 1

Ehtisham Ahmed
Ehtisham Ahmed

Reputation: 387

you can do like this

c=['5*0 4 3 2 5 7 7 3 6 3 2 6 ', ' 8*2 4 5 6 7 8 7 3 7 7 3']
c=[j for i in c for j in i.split()]
print(c)

output

['5*0', '4', '3', '2', '5', '7', '7', '3', '6', '3', '2', '6', '8*2', '4', '5', '6', '7', '8', '7', '3', '7', '7', '3']

Upvotes: 0

Samsul Islam
Samsul Islam

Reputation: 2609

try this

a = open('test.txt', 'r')
b = a.readlines()

new_list = []
for line in b:
    for item in line.strip().split():
        new_list.append(item)
print(new_list)

Upvotes: 1

Related Questions