Created
February 18, 2021 19:37
-
-
Save nmagee/351c219e1364f8e3211a9ea20c87a1d2 to your computer and use it in GitHub Desktop.
Convert TSV to CSV using re.sub
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
#!/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