Skip to content

Instantly share code, notes, and snippets.

@tos-kamiya
Created December 24, 2023 06:59
Show Gist options
  • Save tos-kamiya/6926025f813a94347d08dbaf6bc91c0d to your computer and use it in GitHub Desktop.
Save tos-kamiya/6926025f813a94347d08dbaf6bc91c0d to your computer and use it in GitHub Desktop.
Convert CSV file to LaTeX table
#!/usr/bin/env python3
import argparse
import sys
import os
import pandas as pd
def csv_to_latex(input_file, output_file = None):
# Read csv file
df = pd.read_csv(input_file)
# Convert to LaTeX table format
latex_table = df.style.hide(axis=0).set_table_styles([
{'selector': 'toprule', 'props': ':hline;'},
{'selector': 'midrule', 'props': ':hline;'},
{'selector': 'bottomrule', 'props': ':hline;'},
], overwrite=False).to_latex(clines="all;data")
if output_file is not None:
# Write LaTeX table to the output file
with open(output_file, 'w') as f:
f.write(latex_table)
else:
sys.stdout.write(latex_table)
def main():
parser = argparse.ArgumentParser(description="Convert a CSV file to a LaTeX table.")
parser.add_argument("input_file", nargs='?', type=argparse.FileType('r'), default=sys.stdin, help="Input CSV file path or standard input")
parser.add_argument("-o", "--output", type=str, help="Output file path")
parser.add_argument("-O", "--output_auto", action="store_true", help="Automatically generate the output file name based on the input file name")
args = parser.parse_args()
if args.output and args.output_auto:
raise argparse.ArgumentError(None, "-o and -O options cannot be used together.")
if args.input_file.name == '<stdin>':
raise argparse.ArgumentError(None, "Input file is required. Please provide the input file path or use the -o or -O option.")
if args.output_auto:
base_name, _ = os.path.splitext(args.input_file.name)
output_filename = base_name + '.tex'
elif args.output:
output_filename = args.output
else:
output_filename = None
csv_to_latex(args.input_file, output_filename)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment