Last active
January 21, 2022 10:32
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.")
`