Skip to content

Instantly share code, notes, and snippets.

@nmagee
Created February 18, 2021 19:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nmagee/351c219e1364f8e3211a9ea20c87a1d2 to your computer and use it in GitHub Desktop.
Save nmagee/351c219e1364f8e3211a9ea20c87a1d2 to your computer and use it in GitHub Desktop.
Convert TSV to CSV using re.sub
#!/usr/bin/env python3
import io
import re
def convert(file_name):
# Open csv file
file_name="new_mock_data"
csv = io.open(file_name + ".csv", mode="w", encoding="utf-8")
# Convert file_name.tsv to file_name.csv
with io.open(file_name + ".tsv", mode="r", encoding="utf-8") as tsv:
for line in tsv:
csv.write(re.sub('\t',',',re.sub('(^|[\t])([^\t]*\,[^\t\n]*)', r'\1"\2"', line)))
csv.close()
if __name__ == '__main__':
print('Start converting ...')
convert('table')
print('Converted!')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment