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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With