Search code examples
pythonpandasexport-to-csv

Read CSV file with Python function


I'm trying to write my read/write function to a csv, but it can't return any value.

I'm reading from a CSV, replacing the " ; " in the second column with " " and performing and saving the csv already handled.

But for some reason it doesn't save my csv, is my function wrong?

I'm starting out in the Python world, and I'm having a bit of trouble.

import pandas as pd

header_col = ['col0','col1','col2','col3','col4','col5','col6','col7','col8','col9']
df = pd.read_csv('myfile_<date>.csv', encoding="ISO-8859-1", sep=';', names=header_col, header=None)

def file_load(df):
    df['col1'] = df['col1'].str.replace(';',' ') 
    df.drop(columns=['col8'], inplace=True)
    df.drop(columns=['col9'], inplace=True)
    
    return df

def save_file(dataframe):
    df = dataframe
    df.to_csv('myfile_<date>_treat.csv' ,sep=';', encoding='utf-8', index=False)

Solution

  • import pandas as pd
    
    def file_load(df):
        df['col1'] = str(df['col1']).replace(';',' ') 
        df.drop(columns=['col8'], inplace=True)
        df.drop(columns=['col9'], inplace=True)
        return df
    
    def save_file(dataframe):
        df = dataframe
        df.to_csv('myfile_<date>_treat.csv' ,sep=',', encoding='utf-8', 
        index=False)
    
    
    def main():
        header_col= 
        ['col0','col1','col2','col3','col4','col5','col6','col7','col8','col9']
        df = pd.read_csv('myfile_<date>.csv', encoding="ISO-8859-1", sep=';', 
        names=header_col, header=None)
    
        df1 = file_load(df)
        save_file(df1)
    
    if __name__ == '__main__':
        main()