Header rows are not printed

The header row in jupyter which I have downloaded locally is not being printed even though code is correct I do not know if it is because I did this multiplication of newline by 5 to create more space ( print(headers,"\n" * 5 )) and if that altered the file? However I then reverted:

headers = hn[0]
hn = hn[1:]

for row in hn[:5]:

it should be : [‘id’, ‘title’, ‘url’, ‘num_points’, ‘num_comments’, ‘author’, ‘created_at’]

but displays row after header (which change to different rows every time I execute via shortcut shift+enter:

[‘10482257’, ‘Title II kills investment? Comcast and other ISPs are now spending more’, ‘http://arstechnica.com/business/2015/10/comcast-and-other-isps-boost-network-investment-despite-net-neutrality/’, ‘53’, ‘22’, ‘Deinos’, ‘10/31/2015 9:48’]

it is correct for first code block here, but not the second above. Please advise:
from csv import reader

opened_file = open(‘hacker_news.csv’)
read_file = reader(opened_file)
hn = list(read_file)

for row in hn[0:5]:

Here is the header. :arrow_heading_up: :point_up:

:point_up: Here you removed the header row.

To print the header just :arrow_down::point_down:


The header will be printed.

Hi @jamesberentsen, I used a different dataset to try your code in Jupyter but hopefully it helps you to understand the output you are getting.

You have to include the code which read the original file in the same cell as your code which print header and rows so they are executed simultaneously - see below:

If you don’t do that and you execute your code separately from the code which reads from file, the first time you will get expected result as below:

However, if you execute your code the second time without first running the code which reads from file, since the variable hn is now assigned the value hn[1:] after the first execution, hn[0] does no longer contain the headers but the first row of hn[1:]. That is why at every subsequent running of your code, the header changes - below is the second execution of your code where the code reading from file in cell 1 above is not executed:

Let me know if this helps.

1 Like

Hi enext7771,

Many thanks for your brilliant explanation.
I could not understand why it was not working but do now.


Glad my response was helpful.
Happy learning!