Kevin Julianto
Kevin Julianto

Reputation: 23

delete all .csv file content in python

so, my program will replace the old data with new data which is the program will put in same .csv file. and after i run the program it is not replaced. below is my code.

                        TEXTFILE = open("data.csv", "w")

                        for i in book_list:
                            TEXTFILE.write("{},{},{},{}".format(i[0],i[1],i[2],i[3]))

                        TEXTFILE.close()

book_list is the list that save new data to stored the result i got:

k,k,45,c
a,a,65,r
d,s,65,r
as,as,65,r
df,df6,65,r
as,as,6,r
as,as,46,r
as,as,45,r
as,as,56,rk,k,45,r
a,a,65,r
d,s,65,r
as,as,65,r
df,df6,65,r
as,as,6,r
as,as,46,r
as,as,45,r
as,as,56,r

it stored to csv with combining old and new content.

well the origininal file is looks like this:

k,k,45,r
a,a,65,r
d,s,65,r
as,as,65,r
df,df6,65,r
as,as,6,r
as,as,46,r
as,as,45,r
as,as,56,r

idk how to explain. but I expect that the result will change one line with new data in the fourth row. for example, the previous line is k,k,45,r (line 1). and the program will change it become k,k,45,c that way

hope you all can help me :)

Upvotes: 1

Views: 4611

Answers (1)

UpmostScarab
UpmostScarab

Reputation: 985

Try using .truncate() , if called after opening file it destroys it's content.

TEXTFILE = open("data.csv", "w")
TEXTFILE.truncate()

for i in book_list:
    TEXTFILE.write("{},{},{},{}".format(i[0],i[1],i[2],i[3]))   

TEXTFILE.close()

I hope I understood you correctly.

Upvotes: 1

Related Questions