Home > database >  How to create a csv file in a specific folder in Python?
How to create a csv file in a specific folder in Python?

Time:05-30

I am trying to create a new empty csv file in a specific folder. I can only complete it with two steps. My code is as follows.

#Step 1:Create a new csv file in the current folder.
import csv
csv_name='persons.csv'
with open(csv_name, 'wb') as csvfile:
    filewriter = csv.writer(csvfile, delimiter=',',
                            quotechar='|', quoting=csv.QUOTE_MINIMAL)

#Step 2:Move the new csv file from the current folder to the target folder.
csv_name='persons.csv'
import shutil
path_2=r'C:\Users\jennyhsiao\Technology'
original =path_2 x csv_name "'"
target = r'C:\Users\jennyhsiao\OneDrive'
shutil.move(original, target)

Although the code can successfully create and move the new csv file to the target folder. However, I want to do it with fewer step instead of two steps. Are there any ways to do it?

CodePudding user response:

import os

fileName = "csvFileName.csv"
filePath = "path/to/folder" 

path = os.path.join(filePath, fileName)

with open(path, "w") as csvFile:
    #Do what you want.....

This will work fine ( :

  • Related