python_morsels/fix_csv/fix_csv.py

38 lines
975 B
Python

import logging
from pathlib import Path
logging.basicConfig(level=logging.INFO)
def escape(string):
"""Return an escaped version of `string`."""
string = string.replace('"', '""')
if "," in string:
string = '"' + string + '"'
return string
def normalise(input, output):
"""Normalise `input` CSV file into `output` file."""
Path(output).touch(exist_ok=True)
with Path(input).open("r") as in_file, Path(output).open("w") as out_file:
for in_line in in_file.readlines():
out_elements = [
escape(in_element) for in_element in in_line.strip().split("|")
]
out_file.write(f"{','.join(out_elements)}\n")
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Smol prog to normalise CSV files.")
parser.add_argument("input")
parser.add_argument("output")
args = parser.parse_args()
normalise(args.input, args.output)