How to add a header in a .txt file in 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()
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
Can you show more code? Is this happening in a loop? Or, are you appending to existing file? More context would be helpful.
@DavidZemens This is a general idea, just wanted to see how to get a headline into the text file and store the information into ordered columns and rows. And the code creates a text file for you after running the code.
3 Answers 3
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(''.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.
I think this is close to what he needs, to be 100% sure you are aligned, you will need to aggregate your data first and find the longest entries in each column so you can calculate the remaining or needed space buffer.
Naturally, it was just an example, but thanks for the reminder that the OP might not necessarily understand the implications. I’ve added a line to say it’s not meant to be the exact solution to OPs algorithm.
OK, great this isn’t really what I was expecting. in terms of making it perfectly align I can do but just having a header of the titles at the top of the text file when i want to view them is what I was looking for. so basically when i want to append the file the header is still there.
@MisterBob I’m not sure I understand what the header problem is, then. Can you add more detail to your question? Appending to a file does not delete what was there before. If the file is empty, write the header. If not, just continue with normal appending.
Check to see if the header row already exists, write it in to the file if it doesn’t exist in the first line.
name = input ("Name: ") age = input("Age: ") BirthYear = input("Birth Year: ") filename = "info.txt" header = "Name Age Grade\n" def WriteHeader(filename, header): """ ;param filename: a file path ;param header: a string representing the file's "header" row This function will check if the header exists in the first line and inserts the header if it doesn't exist """ file = open(filename, 'r') lines = [line for line in file] file.close() if lines and lines[0] == header: # There are some lines in the file, and first line is the header return True else: # The first line is NOT the header file = open(filename, w) # Rewrite the file: append header if needed, and all lines which previously were there # excluding any misplaced header lines which were not at row 1 file.write(header + ''.join([line for line in lines if not line == header])) file.close() return True if __name__ == '__main__': if WriteHeader(filename, header): file = open(filename, 'a') file.write("<> / <> / <>\n".format(name, age, BirthYear)) file.close() else: print 'there was some problems. '
On second thought, this is simpler:
def WriteHeader2(filename, header): # Always writes the header. file = open(filename, 'r') # remove any matching 'header' from the file, in case ther are duplicate header rows in the wrong places lines = [line for line in file if not line == header] file.close() # rewrite the file, appending the header to row 1 file = open(filename, w) file.write(''.join([line for line in lines].insert(0,header)) file.close()
Python: What is a header? [closed]
I’m new to Python and programming in general. I am taking a module at university which requires me to write some fairly basic programs in Python. However, I got this feedback on my last assignment:
There should be a header block containing the file name, author name, date created, date modified and python version
What is a header block? Is it just comments at the top of your code or is it be something which prints when the program runs? Or something else?
6 Answers 6
There’s thing called Docstring in python (and here’re some conventions on how to write python code in general — PEP 8) escaped by either triple single quote »’ or triple double quote «»» well suited for multiline comments:
''' File name: test.py Author: Peter Test Date created: 4/20/2013 Date last modified: 4/25/2013 Python Version: 2.7 '''
You also may used special variables later (when programming a module) that are dedicated to contain info as:
__author__ = "Rob Knight, Gavin Huttley, and Peter Maxwell" __copyright__ = "Copyright 2007, The Cogent Project" __credits__ = ["Rob Knight", "Peter Maxwell", "Gavin Huttley", "Matthew Wakefield"] __license__ = "GPL" __version__ = "1.0.1" __maintainer__ = "Rob Knight" __email__ = "rob@spot.colorado.edu" __status__ = "Production"
My Opinion
I use this this format, as I am learning, «This is more for my own sanity, than a necessity.»
As I like consistency. So, I start my files like so.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Created By : Jeromie Kirchoff # Created Date: Mon August 18 18:54:00 PDT 2018 # ============================================================================= """The Module Has Been Build for. """ # ============================================================================= # Imports # ============================================================================= from . import .
- First line is the Shebang
- And I know There’s no reason for most Python files to have a shebang line but, for me I feel it lets the user know that I wrote this explicitly for python3. As on my mac I have both python2 & python3.
- Line 2 is the encoding, again just for clarification
- As some of us forget when we are dealing with multiple sources (API’s, Databases, Emails etc.)
- Line 3 is more of my own visual representation of the max 80 char.
- I know «Oh, gawd why. » again this allows me to keep my code within 80 chars for visual representation & readability.
- Line 4 & 5 is just my own way of keeping track as when working in a big group keeping who wrote it on hand is helpful and saves a bit of time looking thru your GitHub . Not relevant again just things I picked up for my sanity.
- Line 7 is your Docstring that is required at the top of each python file per Flake8.
Again, this is just my preference. In a working environment you have to win everyone over to change the defacto behaviour. I could go on and on about this but we all know about it, at least in the workplace.
Header Block
- What is a header block?
- Is it just comments at the top of your code or is it be something which prints when the program runs?
- Or something else?
So in this context of a university setting:
Header comments appear at the top of a file. These lines typically include the filename, author, date, version number, and a description of what the file is for and what it contains. For class assignments, headers should also include such things as course name, number, section, instructor, and assignment number.
- Is it just comments at the top of your code or is it be something which prints when the program runs? Or something else?
Well, this can be interpreted differently by your professor, showcase it and ask!
«If you never ask, The answer is ALWAYS No.»
# Course: CS108 # Laboratory: A13 # Date: 2018/08/18 # Username: JayRizzo # Name: Jeromie Kirchoff # Description: My First Project Program.
If you are looking for Overkill:
Standard Module Level Dunder Names
__author__ = 'Jeromie Kirchoff' __copyright__ = 'Copyright 2018, Your Project' __credits__ = ['Jeromie Kirchoff', 'Victoria Mackie'] __license__ = 'MSU' # Makin' Shi* Up! __version__ = '1.0.1' __maintainer__ = 'Jeromie Kirchoff' __email__ = 'MyGmailUser@gmail.com' __status__ = 'Prototype'
Add Your Own Custom Names:
__course__ = 'cs108' __teammates__ = ['Jeromie Kirchoff'] __laboratory__ = 'A13' __date__ = '2018/08/18' __username__ = 'JayRizzo' __description__ = 'My First Project Program.'
Then just add a little code to print if the instructor would like.
print('# ' + '=' * 78) print('Author: ' + __author__) print('Teammates: ' + ', '.join(__teammates__)) print('Copyright: ' + __copyright__) print('Credits: ' + ', '.join(__credits__)) print('License: ' + __license__) print('Version: ' + __version__) print('Maintainer: ' + __maintainer__) print('Email: ' + __email__) print('Status: ' + __status__) print('Course: ' + __course__) print('Laboratory: ' + __laboratory__) print('Date: ' + __date__) print('Username: ' + __username__) print('Description: ' + __description__) print('# ' + '=' * 78)
End RESULT
Every time the program gets called it will show the list.
$ python3 custom_header.py # ============================================================================== Author: Jeromie Kirchoff Teammates: Jeromie Kirchoff Copyright: Copyright 2018, Your Project Credits: Jeromie Kirchoff, Victoria Mackie License: MSU Version: 1.0.1 Maintainer: Jeromie Kirchoff Email: MyGmailUser@gmail.com Status: Prototype Course: CS108 Laboratory: A13 Date: 2018/08/18 Username: JayRizzo Description: My First Project Program. # ==============================================================================
Notes: If you expand your program just set this once in the init.py and you should be all set, but again check with the professor.
Your instructor wants you to add some information to your assignment’s source code’s top section something like this, so you are right you will add comments:
#################################### # File name: . # # Author: . # # Submission: # # Instructor: # ####################################
I think it’s a basic introductory programming assignment, therefore adding usual comments will be enough, but definitely she should know docstring.
The Python docstring should be concise, and not really contain revision history, or anything not directly related to the current version behaviour. I have yet to see «man» style docstrings and it may be just as well.
A flower box, with revision history independent of source control (as some of the revisions may pre-date your source control eventually) goes back to the days of reading code on paper or as emailed. We were not always as connected as we are now.
Using a modern IDE this has fallen out of favour, but can be seen for older/larger high level works. In some shops the sign in is not performed by the coder, especially if the code has been «shopped out». Some signin’s are commented in a lazy, slovenly fashion.
#! /usr/bin/python #--------------------------------# # optional flower box #--------------------------------# """ Multiple lines of doc if required """ import foo import bar __metastuff__ = 'some value'
I see the ‘meta‘ higher up, notably in the youtube promotionals for «pycharm». People like to see it below the imports as it is really code and the imports are expected to come before the code. I can imagine it may become easy to get carried away. Sensible and informative comments in the low level code are worth way more than what is written upstairs anyway.
In the real world, just do what everybody else is doing on your project and you will be fine. It is common to re-use a template anyway, or copy and paste (i.e. ripoff) from a «prototype».