prs_wjy
prs_wjy

Reputation: 345

How to make nested list from splited line in txt file?

i want to split every line on my txt file into 3 parts by the space character " ", and make those 3 parts into a list for every line, and make all those lists into a bigger list

my txt file:

1998/04/20 17:38:51.604 16.863014
1998/04/20 17:38:52.204 1.947639
1998/04/20 17:38:54.404 27.278648
1998/04/20 17:39:02.605 0.325151
1998/04/20 17:39:04.705 7.002871

my code:

dataList = []
metaData = ['', '', '']

with open('data.txt', 'r') as myTxt:
    for line in myTxt:
        metaData[0] = line.split(' ')[0]
        metaData[1] = line.split(' ')[1]
        metaData[2] = line.split(' ')[2]
        dataList.append(metaData)
    print(dataList)

i want the output to be like this:

[[1998/04/20, 17:38:51.604, 16.863014],
[1998/04/20, 17:38:52.204, 1.947639],
[1998/04/20, 17:38:54.404, 27.278648],
[1998/04/20, 17:39:02.605, 0.325151],
[1998/04/20, 17:39:04.705, 7.002871]]

but what i got is this:

[[1998/04/20, 17:39:04.705, 7.002871],
[1998/04/20, 17:39:04.705, 7.002871],
[1998/04/20, 17:39:04.705, 7.002871],
[1998/04/20, 17:39:04.705, 7.002871],
[1998/04/20, 17:39:04.705, 7.002871]]

anyone know how to fix this? thx before

Upvotes: 3

Views: 104

Answers (1)

Arkistarvh Kltzuonstev
Arkistarvh Kltzuonstev

Reputation: 6935

Try this :

with open('data.txt', 'r') as myTxt:
    dataList = [i.strip().split() for i in myTxt.readlines()]

Output :

[['1998/04/20', '17:38:51.604', '16.863014'], 
 ['1998/04/20', '17:38:52.204', '1.947639'], 
 ['1998/04/20', '17:38:54.404', '27.278648'], 
 ['1998/04/20', '17:39:02.605', '0.325151'], 
 ['1998/04/20', '17:39:04.705', '7.002871']]

As requested in comment section, for getting the list into another format, try this :

dataList = [[' '.join([i, j]), k] for i,j,k in dataList]

It should output this :

[['1998/04/20 17:38:51.604', '16.863014'], 
 ['1998/04/20 17:38:52.204', '1.947639'], 
 ['1998/04/20 17:38:54.404', '27.278648'],
 ['1998/04/20 17:39:02.605', '0.325151'],
 ['1998/04/20 17:39:04.705', '7.002871']]

If you want to get the above result in one line, you can do this :

with open('test2.txt', 'r') as myTxt:
    dataList = [[' '.join(i.strip().split()[:-1]),i.strip().split()[-1]] for i in in myTxt.readlines()]

Upvotes: 2

Related Questions