how to export a csv dataset to a different directory in python

To export a CSV dataset to a different directory in Python, you can use the following code:

main.py
import os
import shutil
import csv

# Path to the source CSV file
source_file = 'path/to/source_file.csv'

# Path to the destination directory
destination_directory = 'path/to/destination_directory/'

# Create the destination directory if it doesn't exist
os.makedirs(destination_directory, exist_ok=True)

# Generate the path for the destination CSV file
destination_file = os.path.join(destination_directory, 'destination_file.csv')

# Use shutil to copy the source file to the destination directory
shutil.copyfile(source_file, destination_file)
549 chars
19 lines

Replace 'path/to/source_file.csv' with the actual path to your source CSV file and 'path/to/destination_directory/' with the actual path to the directory where you want to export the CSV file.

This code uses the shutil.copyfile function to copy the source CSV file to the destination directory. os.makedirs is used to create the destination directory if it doesn't exist.

Make sure you have the os and shutil modules imported at the beginning of your script.

This code will create a new file named destination_file.csv in the specified destination directory, containing the same data as the source CSV file.

related categories

gistlibby LogSnag