1

I am new to the CSV module in Python and was wondering how to create a CSV file dynamically after a function gets called (it can be an empty CSV file)? The CSV file should be either created (if not existing in the directory) or updated in order to add in data (if found existent). Is there a solution that allows me to create a CSV file regardless of the OS used?

Currently, this is what I had thought of so far:

def create():
    try:                            
          #What should I do here in order to check whether if the file is existent or not?
    except IOError:
          #How to create the CSV file here?
    finally:
          #What should I do here in order to write/append to an existing CSV file?

create()

Can anyone provide a blueprint on how to do this? How can I create a CSV file without manually creating one in my directory?

6
  • why do you need to check fi the file exists? cant you just open the file in append mode anyone and if it doesnt exsit it will create it for youo Commented Nov 22, 2019 at 11:13
  • Oh, I didn't know that. I just want to create an empty CSV file in Python. No data required. How can I do that? Commented Nov 22, 2019 at 11:15
  • your comment doesnt really make sense. are you saying you want a program that will create an empty file and thats it? not put any data in it? Commented Nov 22, 2019 at 11:18
  • Yes! That's it. Afterward, when I wish to add in data, it will just append it to the existing file instead of creating a new one again. This is my requirement. Commented Nov 22, 2019 at 11:19
  • but do you mean in the same program? Commented Nov 22, 2019 at 11:22

4 Answers 4

3

Its fairly simple to just open the file into existence.

import csv

with open(“files.csv”, “a”) as f:
    read_file = csv.writer(f)

The “a” argument will let you append a new line each time you open and add data. Look into these different parameters for writing, and read only, etc to fit your needs. But in answer to your question, this is all you need to create a new empty csv file. You just open it into existence.

https://pythonspot.com/files-spreadsheets-csv/.

Sign up to request clarification or add additional context in comments.

Comments

2

you can open a file in append mode. If it exists it will start adding to the end, if it doesnt exist it will create it. you can then pass that file handle to csv writter. Then you can use the writter to append data later.

import csv
from random import randint

#open the file or create it if it doesnt exist
with open ('test.dat','a', newline='') as my_file:
    csv_writter = csv.writer(my_file)

    #crate some random csv data
    my_data = [[randint(0, 9) for _ in range(10)] for _ in range(10)]

    #for each row append it to our CSV file
    for row in my_data:
        csv_writter.writerow(row)

FILE CONTENT

4,8,8,0,7,5,3,2,7,3
5,0,0,0,2,0,4,1,4,3
0,7,3,7,2,5,7,2,5,7
5,3,5,9,2,9,2,8,9,2
0,1,7,5,8,9,1,2,7,0
2,7,0,1,7,3,0,9,3,4
7,6,4,3,4,2,9,1,7,3
0,9,1,2,8,4,4,6,2,2
8,7,5,7,5,1,9,7,3,9
0,9,1,2,6,3,1,1,6,6

Comments

1

To open a file, the syntax is :

with open('filename.csv', 'x') as file:
    file.write('your,csv,stuff')

The second parameter 'x' specifies that you want to create the file. Note that if it already exists it will produce an error which you'll have to handle.

3 Comments

Thanks for your reply, but how can I create an empty CSV file only (no data)?
You can simply use a pass statement instead of writing stuff in your file.
How can I handle the error if the file exists? Can you demonstrate a basic example in your code, please?
0

directly you can write df to csv

import pandas as pd

df={'id':[1,2,3],'name':['ABC','XYZ','LMN']}
df=pd.DataFrame(df)
df.to_csv('people6.csv',index=False)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.