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

aronsimt
  • 25
  • 10
  • 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? – tdelaney May 12 '20 at 18:45
  • Does this answer your question? [Pythonically add header to a csv file](https://stackoverflow.com/questions/20347766/pythonically-add-header-to-a-csv-file) – Gahan May 12 '20 at 18:46
  • Yes list[0] - data to column user1 – aronsimt May 12 '20 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? – tdelaney May 12 '20 at 18:56
  • photo attached. i want change 1 line to Name: – aronsimt May 12 '20 at 18:58
  • Typing in some text beats a screenshot of a file. It sounds like you have a single column CSV with an existing header and you want to replace it. – tdelaney May 12 '20 at 19:00

2 Answers2

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])
fsrfyama
  • 325
  • 2
  • 13
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)
tdelaney
  • 73,364
  • 6
  • 83
  • 116