Timo
Timo

Reputation: 192

Using user info from text file in Python

I have a file called data.txt with a student numbers and names:

123, Bobbie Smith
456, Suzie Lan
789, Alex Palmer

What i'm trying to achieve is printing these information in sentences like this:

Bobbbie Smith has student number: 123
Suzie lan has student number: 456
Alex Palmer has student number: 789

So what I tried to do is putting every line on data.txt in a seperate list inside a list using:

file = open("data.txt", "r")
studentInfo = file.readlines()
file.close()
lines = [[line] for line in studentInfo]

>>> print(lines)
[['123, Bobbie Smith\n'], ['456, Suzie Lan\n'], ['789, Alex Palmer']]

Is this to good direction or should I do this using a completely different way?

Upvotes: 0

Views: 92

Answers (4)

Chen A.
Chen A.

Reputation: 11280

You don't want to use file as a variable name, as it is a function. So you basically override it (thanks @Mark Tolonen).

You can slightly modify it and use context manager to read the file, and using string.format print the data in a readable fashion

with open("data.txt", "r") as f:
    lines = [line.split(',') for line in f.readlines()]

for s in lines:
    print '{} has student number: {}'.format(s[1].strip(), s[0].strip())

Output:

Bobbie Smith has student number: 123
Suzie Lan has student number: 456
Alex Palmer has student number: 789

I'm striping new lines from line because print statement prints a new line by default for every iteration

Upvotes: 0

BPL
BPL

Reputation: 9863

Here's a couple of ways to achieve what you want using re:

If you don't need to store the processed lines and just wanna print the output directly:

with open("data.txt", "r") as f:
    for l in f.readlines():
        try:
            age, name = re.findall(r'\s*(\d+),\s*(.*)', l)[0]
            print('{} has student number: {}'.format(name, age))
        except:
            pass

If you want to store the processed lines as a list of tuples, maybe something like this would do it:

with open("data.txt", "r") as f:
    lines = [v[0]
             for v in [re.findall(r'\s*(\d+),\s*(.*)', l) for l in f.readlines()] if v]
    for age, name in lines:
        print('{} has student number: {}'.format(name, age))

Upvotes: 0

mjt
mjt

Reputation: 1

one way is using the numpy library

import numpy as np

x, y = np.loadtxt("data.txt", dtype = str, delimiter = ',', unpack = True)
for (i,j) in zip(x,y):
print(j+" has student number: "+i)

Upvotes: 0

Menglong Li
Menglong Li

Reputation: 2255

use csv to avoid strip lines.

import csv

with open('data.txt', 'r', encoding='utf-8') as csv_f:
    reader = csv.reader(csv_f)

    for line in reader:
        print('{x[1]} has student number: {x[0]}'.format(x=line))

Upvotes: 1

Related Questions