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 OverflowCheck the header of the file in python
How to print out http-response header in Python - Stack Overflow
print header for output
python - Print list items with a header - Stack Overflow
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
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))
LAYOUT = "{!s:10} {!s:14} {!s:4} {!s:10}"
yourList = ["Ford","Mustang",1966,"Red"]
print LAYOUT.format("Brand","Modell","Year","Color")
print LAYOUT.format(*yourList)
produces output in columns which will line up (so long as you don't exceed the field width specifiers!), ie
Brand Modell Year Color
Ford Mustang 1966 Red
Mercedes F-Cell 2011 White
You mean:
print 'Brand', 'Modell', 'Year', 'Color'
print ' '.join(yourList)
?
P.S.: Don't name your variable list!
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?