Ikiro
Ikiro

Reputation: 47

Python 3: Extracting Data from a .txt File?

So, I have this file that has data set up like this:

Bob 5 60
Carl 7 80
Rick 8 100
Santiago 7 30

I need to separate each part into three different lists. One for the name, one for the first number, and one for the second number.

But I don't really understand, how exactly do I extract those parts? Also, let's say I want to make a tuple with the first line, with each of the different parts (the name, first number, and second number) into a single tuple?

I just don't get how I extract that information. I just learned how to read and write text files...so I'm pretty clueless.

EDIT: As a note, the text file already exists. The program I'm working on needs to read the text file, which has its data formatted in the way I listed.

Upvotes: 1

Views: 2214

Answers (2)

user890167
user890167

Reputation:

Would not the module Pickle be ideal here? Pickle gives Python functionality to load and save things that need to be 'useable' in Python, so instead of just importing a string from a text file and having to parse it, pickle can load it and give you the actual container you're trying to work with.

example:

import pickle

myList = ["Bob", 1, 2]
listToBeSaved = pickle.dumps(myList) # write this data to your save file
#insert code where you work with the file and save it
#.........    
#upon needing to open and work with this file
listToBeLoaded = open(fileYouWroteTo)
listTranslated = pickle.loads(listToBeLoaded) # turns the loaded data back into a proper list

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121914

You can split each line on whitespace:

with open(yourfile) as f:
    rows = [l.split() for l in f]

names, firstnums, secondnums = zip(*rows)

zip(*iterable) re-arranges the 3 columns into 3 lists.

Upvotes: 5

Related Questions