Argparse throws invalid syntax error despite valid code

39 views Asked by At

I made a working code to perform a function and the output is as intended to be. I tried to convert this code to use argparse to process in command line, (Using Spyder, MacOS) but keep getting :Syntax Error

import pandas as pd
import argparse

def main():
    parser = argparse.ArgumentParser(description='Read file with header only to create emptyDataframe and populate with map entries')
    parser.add_argument('file1', type=str, help='File to map')
    parser.add_argument('file2', type=str, help='File to search')
    parser.add_argument('output', type=str, help='dataframe output')
    args = parser.parse_args()

    # Perform operations on input files and save the result to the output file
    process_files(args.file1, args.file2, args.output)

def process_files(file1, file2, output):
    # Your code to process the input files and save the result to the output file
    df = pd.read_csv(file1, delim_whitespace=True, header=0, index_col=0)

    with open(file2, "r") as f:
        for line in f:
            line = line.strip('\n')
            elements = line.strip().split(" ")
            first_element = elements.pop(0)
            df.loc[first_element] = 'NaN'   
            for each in elements:
                if each in df.columns:
                    df.at[first_element, each] = each  # Match found, assign to corresponding column
                else:
                    pass # Match not found, assign NA

    print("Final dataframe...")
    print(df)
    df.to_csv(output, sep="\t")
    print("DataFrame saved to", output)

if __name__ == '__main__':
    main()

Execution in command-line gives

python3 populate_df_shellv.py to_map.txt to_search.txt populated_dataframe_shell.tsv
  Cell In[20], line 1
    python3 populate_df_shellv.py to_map.txt to_search.txt populated_dataframe_shell.tsv
            ^
SyntaxError: invalid syntax

What is the issue? Please help.

0

There are 0 answers