You don't need to hard-code the header values, just set a variable to the header and test if the new header is different.

last_header = '  '
for value, header in list1:
    if header != last_header:
        print(header, '--------------')
        last_header = header
    print value
Answer from Barmar on Stack Overflow
🌐
Program Creek
programcreek.com › python
Python print headers
def print_headers(names=None, print_file=None): """ Print the MRC header contents from a list of files. This function opens files in permissive mode to allow headers of invalid files to be examined. Args: names: A list of file names. If not given or :data:`None`, the names are taken from the ...
Discussions

Check the header of the file in python
Currently, i am new to python. need some help how to check the header file and check whether the values are present in the oracle table. by disregarding the key word in all the columns and check the rest of the columns and create a warning the column is not present in the table. More on discuss.python.org
🌐 discuss.python.org
4
0
March 28, 2023
How to print out http-response header in Python - Stack Overflow
Today I actually needed to retrieve data from the http-header response. But since I've never done it before and also there is not much you can find on Google about this. I decided to ask my questio... More on stackoverflow.com
🌐 stackoverflow.com
print header for output
I managed to get output for my function, thanks much for your direction. I really appreciate the hints. Now I have tried to place the statement "print ("Length \t" + "Count\n")" in different places in my code so that the function can print the headers only one time in this manner: Count... More on thecodingforums.com
🌐 thecodingforums.com
0
June 19, 2011
python - Print list items with a header - Stack Overflow
If I have a list defined as list=['Ford','Mustang','1966','red'] and try to print it my output would look like: Ford Mustang 1966 red But how can I achieve to have a heading so the output would look More on stackoverflow.com
🌐 stackoverflow.com
December 19, 2010
🌐
GeeksforGeeks
geeksforgeeks.org › python › response-headers-python-requests
response.headers - Python requests - GeeksforGeeks
July 12, 2025 - Python · import requests r = requests.get('https://api.github.com/') # accessing response headers h = r.headers print(h) # accessing a specific header print(h['Content-Type']) Output · GitHub API Headers Output · Explanation: requests.get() function sends an HTTP GET request to the given URL.
🌐
GitHub
gist.github.com › jerblack › 4daade57690dadcb6b1c330fc00295e3
Python table printing function which will print a structured table with headers, defined column widths, automatic text wrapping in columns, and automatic table sizing to fit the table within the terminal width. · GitHub
Python table printing function which will print a structured table with headers, defined column widths, automatic text wrapping in columns, and automatic table sizing to fit the table within the terminal width. - print_table.py
🌐
Python.org
discuss.python.org › python help
Check the header of the file in python - Python Help - Discussions on Python.org
March 28, 2023 - Currently, i am new to python. need some help how to check the header file and check whether the values are present in the oracle table. by disregarding the key word in all the columns and check the rest of the columns a…
🌐
AskPython
askpython.com › home › 3 easy ways to print column names in python
3 Easy Ways to Print column Names in Python - AskPython
November 17, 2020 - We can use pandas.dataframe.columns variable to print the column tags or headers at ease. Have a look at the below syntax! ... import pandas file = pandas.read_csv("D:/Edwisor_Project - Loan_Defaulter/bank-loan.csv") for col in file.columns: print(col) In this example, we have loaded the csv file into the environment. Further, we have printed the column names through a for loop using dataframe.columns variable. ... Python provides us with pandas.dataframe.columns.values to extract the column names from the dataframe or csv file and print them.
🌐
w3resource
w3resource.com › python-exercises › requests › python-request-exercise-4.php
Python: Send a request to a web page, and print the headers information - w3resource
Write a Python program that sends a request to a URL and prints all header information using response.headers, then iterates over the headers to display key-value pairs.
Top answer
1 of 8
28

Update: Based on comment of OP, that only the response headers are needed. Even more easy as written in below documentation of Requests module:

We can view the server's response headers using a Python dictionary:

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

And especially the documentation notes:

The dictionary is special, though: it's made just for HTTP headers. According to RFC 7230, HTTP Header names are case-insensitive.

So, we can access the headers using any capitalization we want:

and goes on to explain even more cleverness concerning RFC compliance.

The Requests documentation states:

Using Response.iter_content will handle a lot of what you would otherwise have to handle when using Response.raw directly. When streaming a download, the above is the preferred and recommended way to retrieve the content.

It offers as example:

>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<requests.packages.urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

But also offers advice on how to do it in practice by redirecting to a file etc. and using a different method:

Using Response.iter_content will handle a lot of what you would otherwise have to handle when using Response.raw directly

2 of 8
14

Here's how you get just the response headers using the requests library like you mentioned (implementation in Python3):

import requests

url = "https://www.google.com"
response = requests.head(url)
print(response.headers) # prints the entire header as a dictionary
print(response.headers["Content-Length"]) # prints a specific section of the dictionary

It's important to use .head() instead of .get() otherwise you will retrieve the whole file/page like the rest of the answers mentioned.

If you wish to retrieve a URL that requires authentication you can replace the above response with this:

response = requests.head(url, auth=requests.auth.HTTPBasicAuth(username, password))
Find elsewhere
🌐
The Coding Forums
thecodingforums.com › archive › archive › python
print header for output | Python | Coding Forums
June 19, 2011 - Now I have tried to place the statement "print ("Length \t" + "Count\n")" in different places in my code so that the function can print the headers only one time in this manner: Count Length 4 7 8 1 12 2 Code so far: def fileProcess(filename = open('declaration.txt', 'r')): """Call the program with an argument, it should treat the argument as a filename, splitting it up into words, and computes the length of each word. print a table showing the word count for each of the word lengths that has been encountered.""" freq = {} #empty dict to accumulate word count and word length print ("Length \t"
🌐
GeeksforGeeks
geeksforgeeks.org › python › get-list-of-column-headers-from-a-pandas-dataframe
Get list of column headers from a Pandas DataFrame - GeeksforGeeks
July 15, 2025 - In this method, we are importing Python pandas module and creating a DataFrame to get the names of the columns in a list we are using the tolist(), function. ... # import pandas library import pandas as pd # creating the dataframe my_df = {'Students': ['A', 'B', 'C', 'D'], 'BMI': [22.7, 18.0, 21.4, 24.1], 'Religion': ['Hindu', 'Islam', 'Christian', 'Sikh']} df = pd.DataFrame(my_df) display("The DataFrame :") display(df) # print the list using tolist() print("The column headers :") print(df.columns.tolist()) # or we could also use # print(df.columns.values.tolist()) # or, # print(df.columns.to_numpy().tolist())
🌐
Reddit
reddit.com › r/learnpython › how do i print the header into a csv file only once?
r/learnpython on Reddit: How do I print the header into a CSV file only once?
November 13, 2018 -

So, I'm trying to make a program where the user has the option to add in a student's details. They provide the first name, last name and student ID, and it gets inserted into a csv file. My initial code was this:

def insert_student():
    print()
    print("Insert a new student:")
    first_name = input("Enter first name:")
    last_name = input("Enter last name:")
    student_id = input("Enter student ID:")

    student_info = {"first_name":first_name,"last_name":last_name,"student_id":student_id}

    import csv
    filePath = "data.csv" 
    with open(filePath, 'a', newline='') as csvfile:
        fieldnames = ['first_name', 'last_name', 'student_id']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({'first_name': first_name,
                         'last_name': last_name,
                         'student_id': student_id})
    print("New Student Record Inserted")

For some reason, it completely skipped filling out the first row of the CSV file, and started from the 2nd row, and it inserted the header every time there was a new entry. I tried following a stackoverflow solution, which checked if the file was empty, then insert the header. If it wasn't empty, it won't print the header. This doesn't work for me, as my file is still 1KB when there's no data on it. Any suggestions on how to make it insert the header once on the first input, and skip the header insertion on subsequent inputs?

🌐
Stack Overflow
stackoverflow.com › questions › 37054421 › print-header-information-for-human-readability-in-python
Print Header Information for Human Readability in Python - Stack Overflow
April 25, 2017 - I learned and code below which gives the Hostnames and Its IP address by the reading the hostname from the "mylabList.txt" file, Now i am looking the way to print the output in a pretty Human readable from Like Column header at the top of each and then the name (Below that).. Is there way to set width between columns while printing... #!/usr/bin/python import sys import socket with open("mylabList.txt", 'r') as f: for host in f: print("{0[0]}\t{0[2][0]}".format(socket.gethostbyname_ex(host.rstrip()))) Current output is Like: mylab1.example.com 172.10.1.1 mylab2.example.com 172.10.1.2 mylab3.example.com 172.10.1.3 mylab4.example.com 122.10.1.4 ·
🌐
Scientifically Sound
scientificallysound.org › 2016 › 10 › 17 › python-print3
Take control of your Python print() statements: part 3 | Scientifically Sound
November 17, 2021 - As I discuss in this post, they are the modern way to print text in Python. ... Like Loading... ... Very nice article. Easy to follow and very instructive. Thank you. ... from collections import namedtuple def print_table(decimal=2): """Function that return text to plot in table format decimal: int Specify number of decimal points to include for data in table """ # Create table header header = ("outcome", "mean", "95 CI") header_filled = f"{header[0]:<12s}{header[1]:>16s}{header[2]:^34s}" markers = "-" * len(header_filled) header = [markers, header_filled, markers] # Create simulated data to include in table names = ['baseline', 'post_10min', 'post_20min'] Estimate = namedtuple('Estimates', ('mean', 'ci')) # namedtuples are great!
🌐
Python Forum
python-forum.io › thread-22054.html
BeautifulTable print header multi times
hello all im trying to code a tool to check the status for all websites in server IP : code : # encoding=utf8 import sys reload(sys) sys.setdefaultencoding('utf8') import requests as qan import time from beautifultable import BeautifulTable import ...
Top answer
1 of 1
1

If you have your HTTP response packet data in http_response_data variable as python bytes type you can get response headers just in one line:

headers_text = http_response_data.partition(b'\r\n\r\n')[0].decode('utf-8')
print(headers_text)

Also you might need to use 'cp852' instead of 'utf-8' if HTTP headers are not UTF-8 encoded.

This takes into account the fact that HTTP headers are separated from HTTP content body by two newlines (all header lines are separated just by one newline).

Next is small example of usage solution above by receiving HTTP bytes response from TCP port 80 of Google's server using standard socket library.

Try it online!

import socket
s = socket.socket()
s.connect(('google.com', 80))
s.send(b'GET / HTTP/1.1\r\n\r\n')
s.shutdown(socket.SHUT_WR)
http_response_data = s.recv(8192) # TCP response stored as bytes
s.close()
headers_text = http_response_data.partition(b'\r\n\r\n')[0].decode('utf-8')
print(headers_text)

PS:

  1. Your headers might be not UTF-8 encoded then instead of .decode('utf-8') try other encoding/code-page like this .decode('cp852').
  2. headers_text will contain also status line like HTTP/1.1 200 OK if you don't need it (if important to have only key: value lines) you can use next code instead:
headers_text = http_response_data.partition(b'\r\n\r\n')[0].partition(b'\r\n')[2].decode('utf-8')
print(headers_text)
  1. According to your tutorial TCP data as bytes type is available at the end of body of if protocol == 6 : block as data variable, use it as http_response_data in my solution.
🌐
Sentry
sentry.io › sentry answers › python › make a list of the column headers in a python pandas dataframe
Make a list of the column headers in a Python Pandas DataFrame | Sentry
November 15, 2023 - How can I create a list of the column headers in a Python Pandas DataFrame? The simplest way to do this is by directly casting the DataFrame to a list: import pandas data = { "A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9] } df = pandas.DataFrame(data) column_names = list(df) print(column_names) # will print ['A', 'B', 'C']
🌐
Kaggle
kaggle.com › questions-and-answers › 67692
How to print column header names vertically in pandas ...
Checking your browser before accessing www.kaggle.com · Click here if you are not automatically redirected after 5 seconds