1

Can you help me please. how to add column name to csv file with python.

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'csvfile.csv')
file_exists = os.path.isfile(csvfilename)
f = open(csvfilename,'a')
f.write(list[0] + ';' + '\r\n')
f.close()

enter image description here

6
  • 1
    By column name, do you mean you want a header in the first line of the file? What is list[0]? Is it a list containing multiple column names? Commented May 12, 2020 at 18:45
  • Does this answer your question? Pythonically add header to a csv file Commented May 12, 2020 at 18:46
  • Yes list[0] - data to column user1 Commented May 12, 2020 at 18:54
  • Do you have an example CSV file? Just a few lines would do. Is there an existing header? Is this a semicolon separated file? Commented May 12, 2020 at 18:56
  • photo attached. i want change 1 line to Name: Commented May 12, 2020 at 18:58

2 Answers 2

3

may be you can add a header like this?

with open(csvfilename, 'wt', newline ='') as file:
    write_header = csv.writer(file, delimiter=',')
    write_header.writerow(i for i in list[0])
Sign up to request clarification or add additional context in comments.

Comments

0

Since you just want to modify a single line of the file there isn't a need to run this all through a CSV processor. Its generally best not to read and write to the same file. You can create a temporary file and make the changes to the top of the file before copying the bulk.

import shutil

dirname = os.path.dirname(os.path.abspath(__file__))
csvfilename = os.path.join(dirname, 'csvfile.csv')
tmpfilename = os.path.join(dirname, 'csvfile.csv.tmp')
file_exists = os.path.isfile(csvfilename)

with open(csvfilename, 'rb') as f_in, open(tmpfilename, 'wb') as f_out:
    # discard current header
    next(f_in)
    # write new header
    f_out.write("colname\r\n".encode())
    # copy the rest of the file
    shutil.copyfileobj(f_in, f_out)
# replace original csv with fixed
shutil.move(tmpfilename, csvfilename)

Comments

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.