Read and Store data from csv file in Python


In your python development, there are many instances when you need to read some data from CSV or may need to store results (final or intermediate) to csv files, So in this article we will see some ways to read and store Pandas dataframe in csv files.
 

 import pandas as pd

df = pd.DataFrame({'column1': [2, 4, 8, 0],
                   'column2': [6, 0, 0, 0],
                   'column3': [10, 2, 1, 8],
                   'column4': [14, 5, 32, 68]})
df.to_csv("temp.csv", index=False)
print(pd.read_csv("temp.csv"))
# print Dataframe
print(df) 

if you want to raed csv line by line then use csv package as below:


import csv

with open('temp.csv') as csv_file:
    csv_reader = csv.reader(csv_file, delimiter=',')
    line_count = 0
    for row in csv_reader:
        if line_count == 0:
            print(f'Column names are {", ".join(row)}')
            line_count += 1
        else:
            print(f'{row}')
            line_count += 1
    print(f'Total {line_count} lines processed.')

Happy Python coding.

Comments

Popular posts from this blog

Pinescript Code for Hilega Milega

Sending message to Telegram Group, User or Bot using Python

Pine script for Intraday backtesting Previous Day high and Previous Day Low Breakout strategy