Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a header in a .txt file in Python

Tags:

python

I am trying to add a permanent header for a text file and along with the headers there should be the corresponding information i.e:

My code snippet:

name = input ("Name: ")
age = input("Age: ")
BirthYear = input("Birth Year: ")

file = open ("info.txt", "a")
file.write ("Name Age Grade\n")
file.write ("{} / {} / {}\n".format(name, age, birthYear))
file.close()

So far the code just outputs the following into a text file :

Name Age BirthYear
name / 16 / 1999

the header is not permanently on the top of the page. The corresponding information of each header should align to the headers; I would like it to look something like the following:

Name    Age  BirthYear  
Sam     22   1993
Bob     21   1992

it has to be in a text file.

like image 202
Mister Bob Avatar asked Mar 14 '23 11:03

Mister Bob


2 Answers

What about just opening the file and writing in the header and then using a new with block to loop through and write in the individual records? I came across your question as I also needed to print a header into my csv text file. Eventually I just did the following (using your example):

header = "Name, Age, BirthYear"

with open('results.txt', 'a') as f:
    f.write(header + "\n")
    f.close

with open('results.txt', 'a') as f:

    for x in rows_sub:
        f.write(str(x) + ", " + c + "\n") #the line I needed to have printed via a loop
like image 98
San990 Avatar answered Mar 24 '23 05:03

San990


text files do not have a header. If you want a true header, you'll need a more complex format. Alternatively, if you just need something that acts like a header, then you need to figure out how many characters fit on your page vertically, and print the header every N lines.

For horizontal alignment, make use of the extra tokens you can use with format(). As an example:

>>> print('{a:^8}{b:^8}{c:^8}'.format(a='this', b='that', c='other'))
  this    that   other 

where ^8 says I want the string centered across 8 characters. Obviously you have to choose (or derive) the value that works for your data.

like image 42
BlivetWidget Avatar answered Mar 24 '23 06:03

BlivetWidget