1

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 :)

7
  • 1
    If you could please post what the original file looks like, and your expected output, that would help Commented Nov 3, 2017 at 18:59
  • fixed, sorry I have a bit obstacles to edit the post. Commented Nov 3, 2017 at 19:18
  • Also post the expected "new content". It would also be helpful to know what the variable book_list looks like. Commented Nov 3, 2017 at 19:23
  • @KevinJulianto that is very strange. I cannoit reproduce your issue at all. Could it be that the problem is in other part of your code? For example maybe you somehow duplicate contents of book_list. Please make sure that book_list has what you want it to. Commented Nov 3, 2017 at 19:35
  • nope, I just want to write the new data into the same csv file Commented Nov 3, 2017 at 19:36

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

I already change the "w" with "w+" but the result still same. but thankyou btw :)
@KevinJulianto so did I understood what you are trying to do? You want to overwrite contents?
@KevinJulianto please try the new version of my code.
@UpmostScarab, w mode should also truncate the file so this shouldnt change anything
You can write (*i[0:4]) too shorten.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.