0

I am looking to copy only the first row(headers) of a csv file as row in a new file.

I currently have this piece of code which transposes the entire file and writes it into a new file.

But my requirement is only to have the headers of a csv file into another skipping the first row entirely.

import pandas as pd
pd.read_csv('Cars.csv', header=None).T.to_csv('output.csv', header=False, index=False)
2
  • pass nrows=1 to read_csv. Commented Oct 9, 2020 at 17:37
  • .iloc[0] or .columns() without the header=None would also work Commented Oct 9, 2020 at 17:39

1 Answer 1

1

You can get the headers (first row) much more efficiently without pandas:

with open("Cars.csv", 'r') as fid:
    header_list = fid.readline().strip().split(",")

with open("out.csv", 'w') as fid:
    fid.write("\n")
    fid.write("\n".join(header_list))
Sign up to request clarification or add additional context in comments.

7 Comments

Apologies I wanted them the headers in a column in a new file. I wrote rows by mistake. Apologies for the confusion
changed it so now the code is reading the first line out of "cars.csv" and writing that line into "out.csv"
I am getting an error fid.write(header_line) io. UnsupportedOperation : not writeable error
Just one last thing currently I am reading my data in row. Can it be re- arranged into columns please
You got that error because I forgot the "w" when opening the second file. Thanks for the edit! What do you mean by "No Company Car Model"?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.