(Feb-05-2022, 12:08 AM)bowlofred Wrote:writerow()
takes exactly one argument: the entire row you want to write/append to your csv.
You've passed in two objects. If you want to addrecord_index
to your CSV, modifyrow
directly to put that value in the row. Then write that row out.
Some other things I might suggest:
You don't need two separate contexts to open two files. If you're just going to exit immediately if either open fails and you're done with them at the same time, then you might want to put them in the samewith
and save some indent space.
Since you're just counting on a loop, consider using enumerate() for a counter rather than managing your own.
import csv import glob header = ['NAME','ADDRESS','PHONE','EMAIL'] # with pipe delimter data with open("datafile.txt", mode='r') as text_pipe, open("output.csv", 'w', newline= '') as file_comma: reader_pipe = csv.reader(text_pipe, delimiter = '|') writer_delim = csv.writer(file_comma, delimiter = ',') writer_delim.writerow(header) # add header for record_index, row in enumerate(reader_pipe, 1): # loop to read file row.insert(0, record_index) writer_delim.writerow(row) # print value in each line
It works perfectly bowlofred! Thank you!
What I learn:
1. to write in same 'with'
2. function 'insert'
3. I've tried 'enumerate' before but haven't absorbed it until now.
Extra question.
1. So if i want to insert other values and add new columns or fields, i can just use insert function and use position?
2. Do you have suggestion how to truly understand these types of functions or just practice?