python
I want to write a new CSV file with headers if it does not exist, and append row data to it. Not sure why the following code doesn't add the file headers? (Append works fine)
import os
import csv
path = "test.csv"
with open(path, mode="a") as f:
writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
if not os.path.exists(path):
writer.writerow(["col1", "col2", "col3", "col4", "col5", "col6", "col7"])
row = [1,2,3,4,5,6,7]
writer.writerow(row)
Need to move if exists test before opening the file. Opening the file in "a" mode will create the file if it does not already exist.
import os
import csv
path = "test.csv"
exists = os.path.exists(path)
with open(path, mode="a") as f:
writer = csv.writer(f, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
if not exists:
writer.writerow(["col1", "col2", "col3", "col4", "col5", "col6", "col7"])
row = [1,2,3,4,5,6,7]
writer.writerow(row)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.