Python create csv file if not exist

I want to know how to create a file if it does not exist in the directory. I want to only append data.

I am getting this error in Python: No such file or directory.

This is my code:

with open [saveAddr+".csv",'a'] as allpckts:                            
    writer = csv.DictWriter[allpckts, delimiter=',', fieldnames=header] 
    if pktnum < 2:                                                        
        writer.writerow[dict[[fn,fn] for fn in header]]                 
        writer.writerow[packet_data]                                    
    else:                                                               
        writer.writerow[packet_data]    

Update: My problem was that I wasn't in right directory. So for anyone searching for the most basic syntax to only append to CSV file is:

with open [filename+".csv",'a'] as filedata:                            
    writer = csv.DictWriter[filedata, delimiter=',', fieldnames=header]
    writer.writerow[data] 

asked Aug 19, 2015 at 6:10

6

Most probably you are trying to create a file in a directory which does not exist .

What you want is what 'a' mode does , it creates the file if it does not exist , otherwise it appends to the file . But it would not create the directories , if those directories so not exist , you should create the directories used in saveAddr , before running the program .

If you want a programmatic solution , you can check out os.mkdir , which should create the directory.

answered Aug 19, 2015 at 6:20

Anand S KumarAnand S Kumar

84.8k18 gold badges178 silver badges169 bronze badges

with open [saveAddr+".csv",'a'] as allpckts:

will create a new file saveAddr+".csv" if not exist, otherwise open it for further appending.Assuming saveAddr is the file name[if path includes in it, check whether path exists.]

If you want to check file exists

os.path.isfile['/path/to/csv']

answered Aug 19, 2015 at 6:16

itzMEonTVitzMEonTV

19.1k3 gold badges38 silver badges48 bronze badges

0

#check if dir exist if not create it
def check_dir[file_name]:
    directory = os.path.dirname[file_name]
    if not os.path.exists[directory]:
        os.makedirs[directory]


def save[file_name, records]:
    check_dir[file_name]
    csv_file = open[file_name,'w+']
    csvWriter = csv.writer[csv_file,delimiter=',']
    count = 0
    for record in records:
        csvWriter.writerow[[record]]
        count+=1

    print[count, " record saved to ",file_name]
    return  count    enter code here

directory = os.path.abspath[os.path.join[os.path.curdir]]
save[directory+"/data/filename.csv",your_list]

answered Apr 14, 2018 at 16:23

1._

with open[saveAddr + ".csv", 'a'] as allpckts:

If you want to check file exists

os.path.isfile['/path/to/csv']

#check
if dir exist
if not create it
def check_dir[file_name]:
   directory = os.path.dirname[file_name]
if not os.path.exists[directory]:
   os.makedirs[directory]

def save[file_name, records]:
   check_dir[file_name]
csv_file = open[file_name, 'w+']
csvWriter = csv.writer[csv_file, delimiter = ',']
count = 0
for record in records:
   csvWriter.writerow[[record]]
count += 1

print[count, " record saved to ", file_name]
return count enter code here

directory = os.path.abspath[os.path.join[os.path.curdir]]
save[directory + "/data/filename.csv", your_list]


In this article, we will discuss how to append a row to an existing csv file using csv module’s reader / writer & DictReader / DictWriter classes.,This writer object has a function writerow[] , pass the list to it and it will add list’s contents as a new row in the associated csv file,csv module provides a class writer, which can write lists into csv file as rows. Let’s see how to use it for appending a new row in csv,,csv module provides a class DictWriter, which can write dictionaries into csv file as rows. Let’s see how to use it for appending a new row in csv,

Suppose we have a CSV file students.csv, whose contents are,

Id, Name, Course, City, Session
21, Mark, Python, London, Morning
22, John, Python, Tokyo, Evening
23, Sam, Python, Paris, Morning

Suppose we have a list of strings,

# List of strings
row_contents = [32, 'Shaun', 'Java', 'Tokyo', 'Morning']

The above steps will append out list as a row in the csv. To make the process simple, we have created a separate function with the above steps,

from csv
import writer

def append_list_as_row[file_name, list_of_elem]:
   # Open file in append mode
with open[file_name, 'a+', newline = ''] as write_obj:
   # Create a writer object from csv module
csv_writer = writer[write_obj]
# Add contents of list as last row in the csv file
csv_writer.writerow[list_of_elem]


Last Updated : 26 Nov, 2020,Technical Scripter 2020

Let’s take one List that we want to add as a new row.

List = [6, 'William', 5532, 1, 'UAE']

Let’s take one Dictionary that we want to add as a new row.

dict = {
   'ID': 6,
   'NAME': 'William',
   'RANK': 5532,
   'ARTICLE': 1,
   'COUNTRY': 'UAE'
}


This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it is overwritten.,This method is not entirely safe. If an exception occurs when we are performing some operation with the file, the code exits without closing the file.,Writing a string or sequence of bytes [for binary files] is done using the write[] method. This method returns the number of characters written to the file.,In this tutorial, you'll learn about Python file operations. More specifically, opening a file, reading from it, writing into it, closing it, and various file methods that you should be aware of.

Python has a built-in open[] function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly.

>>> f = open["test.txt"] # open file in current directory >>>
   f = open["C:/Python38/README.txt"] # specifying full path

2._

f = open["test.txt"] # equivalent to 'r'
or 'rt'
f = open["test.txt", 'w'] # write in text mode
f = open["img.bmp", 'r+b'] # read and write in binary mode

Hence, when working with files in text mode, it is highly recommended to specify the encoding type.

f = open["test.txt", mode = 'r', encoding = 'utf-8']


If the file you specified does not exist, then the writing function creates and writes data to a new file.,If the file you specified does not exist, then the writing function creates a new file and writes the input data to the first sheet.,'overwrite' [default] — Overwrite the file.,If the file you specified does not exist, then the writing function performs the same actions as 'replacefile'.

T = table[['M';
   'F';
   'M'
], [45 45;41 32;40 34], ...{
   'NY';
   'CA';
   'MA'
}, [true;false;false]]

T = 3× 4 table
Var1 Var2 Var3 Var4
____ ________ ______ _____

M 45 45 {
   'NY'
}
true
F 41 32 {
   'CA'
}
false
M 40 34 {
   'MA'
}
false

Var1, Var2_1, Var2_2, Var3, Var4
M, 45, 45, NY, 1
F, 41, 32, CA, 0
M, 40, 34, MA, 0

writetable[T, 'myData.txt', 'Delimiter', ' ']
type 'myData.txt'


How do you create csv file in Python If not exist?

The 4 Steps to Writing a CSV in Python.
Open a CSV file in the write mode. This happens using the open[] function. ... .
Create a CSV writer object. To do this, create a csv module's writer[] object, and pass the opened file as its argument..
Write data to the CSV file. ... .
Close the CSV file using the close[] method of a file..

How do you write to a nonexistent file in Python?

Using a Write mode “w” or “w+” will create a file if not exists in Python. Or use this code first check file exists or not, then do create it.

Which mode create new file if the file does not exist in Python?

To create a new file in Python, use the open[] method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist. "a" - Append - will create a file if the specified file does not exist. "w" - Write - will create a file if the specified file does not exist.

When you open a file for reading in Python If the file does not exist?

When you open a file for reading, if the file does not exist, the program will open an empty file.

Chủ Đề