Skip to content

Instantly share code, notes, and snippets.

@Stevoisiak
Last active January 21, 2022 10:32
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save Stevoisiak/c79c75a4c2f28d92de9077a48360d68d to your computer and use it in GitHub Desktop.
Save Stevoisiak/c79c75a4c2f28d92de9077a48360d68d to your computer and use it in GitHub Desktop.
Python script to convert a comma-delimited CSV to a tab-delimited file. (Drag & Drop)
import csv
import sys
import os
# Convert comma-delimited CSV files to pipe-delimited files
# Usage: Drag-and-drop CSV file over script to convert it.
inputPath = sys.argv[1]
outputPath = os.path.dirname(inputPath) + "/output.csv"
# https://stackoverflow.com/a/52410395/3357935
print("Converting CSV to tab-delimited file...")
with open(inputPath) as inputFile:
# newline='' prevents extra newlines when using Python 3 on Windows
# https://stackoverflow.com/a/3348664/3357935
with open(outputPath, 'w', newline='') as outputFile:
reader = csv.DictReader(inputFile, delimiter=',')
writer = csv.DictWriter(outputFile, reader.fieldnames, delimiter='|')
writer.writeheader()
writer.writerows(reader)
print("Conversion complete.")
@p4ulynn
Copy link

p4ulynn commented Dec 7, 2021

Thanks man! That helped me a lot! I transformed it a little bit: I changed the input method and I wanted to convert semicolon- to comma-delimited csv files. See my script attached.
`
import csv
import sys
import os

Convert semicolon-delimited CSV files to comma-delimited files

Usage: Enter input semicolon-delimited CSV file in the console to convert it to a comma-delimited CSV file

#select input file (semicolon delimited csv file)
user_input = input("Enter the path of your file: ")

assert os.path.exists(user_input), "I did not find the file at, " + str(user_input)
f = open(user_input, 'r+')
print("Hooray we found your file!")

stuff you do with the file goes here

f.close()

inputPath = user_input
outputPath = os.path.dirname(inputPath) + "/output.csv"

print("Converting CSV to comma-delimited file...")
with open(inputPath) as inputFile:
# newline='' prevents extra newlines when using Python 3 on Windows
with open(outputPath, 'w', newline='') as outputFile:
reader = csv.DictReader(inputFile, delimiter=';')
writer = csv.DictWriter(outputFile, reader.fieldnames, delimiter=',')
writer.writeheader()
writer.writerows(reader)
print("Conversion complete.")
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment