Home > database >  Python: Separate text file data into tuples?
Python: Separate text file data into tuples?

Time:11-16

I'm currently working on trying to separate values inside of a .txt file into tuples. This is so that, later on, I want to create a simple database using these tuples to look up the data. Here is my current code:

with open("data.txt") as load_file:
    data = [tuple(line.split()) for line in load_file]

c = 0
pts = []
while c < len(data):
    pts.append(data[c][0])
    c  = 1
    print(pts)
    pts = []

Here is the text file:

John|43|123 Apple street|514 428-3452
Katya|26|49 Queen Mary Road|514 234-7654
Ahmad|91|1888 Pepper Lane|

I want to store each value that is separated with a "|" and store these into my tuple in order for this database to work. Here is my current output:

['John|43|123']
['Katya|26|49']
['Ahmad|91|1888']

So it is storing some of the data as a single string, and I can't figure out how to make this work. My desired end result is something like this:

['John', 43, '123 Apple street', 514 428-3452]
['Katya', 26, '49 Queen Mary Road', 514 234-7654]
['Ahmad', 91, '1888 Pepper Lane', ]

CodePudding user response:

try with this:

with open("data.txt") as load_file:
    data = [line.strip('\n').split('|') for line in load_file]
for elem in data:
    print(elem)

CodePudding user response:

Try to use csv module with custom delimiter=:

import csv

with open("your_file.txt", "r") as f_in:
    reader = csv.reader(f_in, delimiter="|")

    for a, b, c, d in reader:
        print([a, int(b), c, d])

Prints:

['John', 43, '123 Apple street', '514 428-3452']
['Katya', 26, '49 Queen Mary Road', '514 234-7654']
['Ahmad', 91, '1888 Pepper Lane', '']
  • Related