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.

Related Question “File Does Not Exist” when dynamically creating files for PDF download with Requests in Python 2.7 “Python exec is not exist” when creating new project in Cocos Studio Error when creating a new text file with python? Idiom in python for opening second file when the first file does not exist Creating a new file in Python Python open says file doesn't exist when it does Python throws an error that file doesn't exist when it clearly does Python: FileNotFoundError: [Errno 2] No such file or directory: when directory does exist Does Python use pointers when creating a new sliced list? Python file does not exist exception
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM