Turning a text file into a tabular format [duplicate]

2024/11/15 19:37:36

I'm having issues trying to properly format a text file to fit the needed criteria for a school project. I've been stuck on it for a while and I'm still very new to coding and wanted to know if anyone has an answer that I can understand and implement, hopefully I can learn from those much more experienced.

I want to convert a text file that can be entered by a user that looks like this within the file:

Lennon 12 3.33
McCartney 57 7
Harrison 11 9.1
Starr 3 4.13

and create it to fit a tabular format like this:

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

I can create the headers, though it may not be pretty code, but when I print the contents of the test file it usually turns out like this:

Name            Hour      Total pay
Lennon 12 3.33
McCartney 57 7
Harrison 11 9.1
Starr 3 4.13

And I don't understand how to properly format it to look like a proper table that's right justified and properly in line with the actual headers, I'm not sure how to really tackle it or where to even start as I haven't made any real ground on this.

I've gutted my code and broke it down into just the skeleton after trying with things like file_open.read().rstrip("\n) and .format making a mess of the indexes and sometimes somehow ending up with only single letters to appear:

file_name = input("Enter the file name: ")print("Name" + " " * 12 + "Hour" + " " * 6 + "Total pay")
with open(file_name, 'r') as f:for line in f:print(line, end='')

I know it looks simple, and because it is. Our instructor wanted us to work with the "open" command and try and stay away from things that could make it less readable but still as compact as possible. This includes the importing of third party tools which shot down chances to use things like beautifultable like a few other friends have offered as an easier way out.

I had a classmate say to read the lines that turns it into a list and adjust it from there with some formatting, and another classmate said I could probably format it without listing it; although I found that the newline character "\n" appears at the end of each list index if turning it into a list

ex: ['Lennon 12 3.33\n', 'McCartney 57 7\n', 'Harrison 11 9.1\n', 'Starr 3 4.13']

Though what I don't understand is how to format the things that are within the list so that the name can be separated from each of the number variables and in line with the header as I don't have much experience with for loops that many say can be an easy fix within my class if I have that down pat.

I'm not exactly looking for straight coded answers, but rather a point in the right direction or where to read up on how to manipulate listed content

Answer

Here's something to get you headed in the right direction:

data_filename = 'employees.txt'
headers = 'Name', 'Hours', 'Rate'  # Column names.# Read the data from file into a list-of-lists table.
with open(data_filename) as file:datatable = [line.split() for line in file.read().splitlines()]# Find the longest data value or header to be printed in each column.
widths = [max(len(value) for value in col)for col in zip(*(datatable + [headers]))]# Print heading followed by the data in datatable.
# (Uses '>' to right-justify the data in some columns.)
format_spec = '{:{widths[0]}}  {:>{widths[1]}}  {:>{widths[2]}}'
print(format_spec.format(*headers, widths=widths))
for fields in datatable:print(format_spec.format(*fields, widths=widths))

Output:

Name       Hours  Rate
Lennon        12  3.33
McCartney     57     7
Harrison      11   9.1
Starr          3  4.13
https://en.xdnf.cn/q/119018.html

Related Q&A

Python: Read file with list as list

I have placed a list in a text file. I want python to read the text file and return the contents as a list. However, it is instead reading the content as a string:Text file:[a,b,c]Python:ids=[]writtenF…

Tkinter scrollbar not scrollable

I followed some tutorial on attaching a scrollbar to a textbox. However, in the tutorial, the scrollbar is really a "bar". When I tried myself, I can only press the arrows to move up or down,…

How to create multiple roles through discord.py bot?

I have been trying to make my discord bot create multiple roles through a command. But it simply doesnt work. Here is what I have done so far: @commands.command()async def create_roles(self, ctx):guild…

python: how do i know when i am on the last for cycle

for i in range(len(results_histogram)):if i!=len(results_histogram)-1:url+=str(results_histogram[i])+,my if statement is checking whether i am on the last loop, but it is not working. what am i doing w…

scrape text in python from https://brainly.co.id/tugas/148

scrape "Jawaban terverifikasi ahli" in green box from the url https://brainly.co.id/tugas/148, possibly the color of green tick icon to the left of it also(tag <use xlink:href="#icon-…

Percentage of how similar strings are in Python? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic…

A Python dictionary with repeated fields

Im constructing a dictionary with Python to use with a SOAP API.My SOAP API takes an input like this:<dataArray><AccountingYearData><Handle><Year>string</Year></Handle&…

psexec run python script passed from host

I am trying to run a python script on a remote computer via psexec. I am able to connect and run python.exe with the following:C:\test>psexec \\192.168.X.X -u domain\administrator -p password -i C:…

TypeError: main() missing 1 required positional argument: self

My code and error is below and I was trying to understand why I am getting the error and how to fix it. I tried this without self and got another error TypeError: load_data() takes 0 positional argumen…

Python not calling external program

I am having problems with a python program that I wrote. It is actually plpython3u. I am running the program as a Trigger from postgres. I am pretty sure the trigger part works. My test python prog…