user12691511
user12691511

Reputation:

How to make an array/table in python from a text file

data.txt file:

Lambert 34 10.50
Osborne 22 6.25
Giacometti 5 100.70
f = input("Enter the file name: ")

f1 = open(f, 'r')

print("Name"  ,   "Hours",   "Total Pay")

for line in f1:
    print(line)

current output:

Enter the file name: data.txt
Name Hours Total Pay
Lambert 34 10.50

Osborne 22 6.25

Giacometti 5 100.70

The issue with this code is that it needs to be printed out in tabular format. With headers of name, hours, total pay, with the contents of the file under it.

I know how to open the file, and print it by line, but I have no idea how I am going to make it like a table format. An example of the output is going to be like this:

Enter the file name: data.txt

Name            Hours      Total Pay
Lambert            34         357.00
Osborne            22         137.50
Giacometti          5         503.50

How would I do this? I'm almost there, I'm pretty sure I need to make my first print statement longer, and make an array, such as this from another stack overflow post

data = np.array([[1, 2, 1],
                 [0, 1, 0],
                 [2, 4, 2]])

But the issue is how would I make an array from contents from a text file?

Thank you

Upvotes: 0

Views: 1126

Answers (3)

bashBedlam
bashBedlam

Reputation: 1500

This is how I would go about it :

filename = input("Enter the file name: ")

items = []
try :
    with open (filename, 'r') as datafile :
        print("Name", "          Hours", "    Total Pay")
        for line in datafile :
            items = line.strip ('\n').split (' ')
            tab1 = ' ' * (18 - (len (items [0]) + len (items [1])))
            tab2 = ' ' * (12 - len (items [2]))
            print (items [0], tab1, items [1], tab2, items [2])
except OSError :
        print ('File ERROR occured.')
        print (filename, ' has not been loaded.')

Screen shot of output

Upvotes: 0

i_am_deesh
i_am_deesh

Reputation: 486

 import numpy as np
 data = np.genfromtxt("data.txt")

you can do this

if you want to skip the initial lines import numpy as np data = np.genfromtxt("data.txt")

or you can use pandas as well for this purpose

import pandas as pd
data = pd.read_csv("data.txt", sep=" ")

this should also work

Upvotes: 0

Shubham Shaswat
Shubham Shaswat

Reputation: 1310

I have modified the code of @rpanai to add columns name to suit your answer

df = pd.read_csv('data.txt', delim_whitespace=True, names=['Name', 'Hours', 'Total Pay'])

Upvotes: 1

Related Questions