royal
royal

Reputation: 51

How write and append data in csv file and store it in list

I made csv file in my python code itself and going to append next data in ti it but the error is comming

io.UnsupportedOperation: not readable 

I tried code is:

df.to_csv('timepass.csv', index=False)
with open(r'timepass.csv', 'a') as f:
       writer = csv.reader(f)
       your_list = list(writer)
       print(your_list)

want to append next data and store in the same csv file. so that csv file having both previous and current data. so please help me to find out.. Thanks in advance...

Upvotes: 1

Views: 1073

Answers (4)

vishalk
vishalk

Reputation: 182

you can use pandas for appending two csv quickly

import pandas as pd
dataframe1=pd.read_csv("a.csv")
dataframe2=pd.read_csv("b.csv")
dataframe1=dataframe1.append(dataframe2)
dataframe1=dataframe1.reset_index(drop=True)
dataframe1.to_csv("a.csv")

Upvotes: 1

BernardL
BernardL

Reputation: 5444

Try:

with open(r'timepass.csv', 'r') as f:
    reader = list(csv.reader(f))

print(reader)

Here you are opening your file as r, which means read-only and assigning the list contents to reader with list(csv.reader(f)). Your earlier code a opens the file for appending only where in the documentation is described as:

'a' opens the file for appending; any data written to the file is automatically added to the end

and does not support the read().

And if you want to append data to the csv file from a different list, use the with open as a with the writer method.

with open('lake.csv','a') as f:
    csv.writer(f,[1,2,3]) #dummy list [1,2,3]

Or directly from the pandas.DataFrame.to_csv method from your new dataframe, with header = False so as not to append headers:

df.to_csv('timepass.csv', index=False)
df_new.to_csv(r'timepass.csv', mode='a', header=False) #once you have updated your dataframe, you can directly append it to the same csv file

Upvotes: 1

Karthick Aravindan
Karthick Aravindan

Reputation: 1102

Please check this.

You can use pandas in python to read csv and write csv:

import pandas as pd 

df = pd.read_csv("csv file")

print(df)

Upvotes: 1

Sachin
Sachin

Reputation: 1704

It is so simple just try this:

import pandas as pd

df = pd.read_excel("NSTT.xlsx","Sheet1")  #reading Excel 

print(df)    #Printing data frame 

df.to_excel("new.xlsx")    #Writing Dataframe into New Excel file 

Now here if you want to append data in the same file then use

df.to_excel("new.xlsx","a")

And no need to add in a list as you can directly access the data same as a list with data frame only you have to define the location .

Upvotes: 1

Related Questions