0

I'm trying to make a program that updates a csv row by the 0-9 range which would be the ID Number. So after it searches for the id number, it prompts the user to enter the replacement values as you can see on the replace part of this code below. Since csv is comma separated i connected the strings with comma alongside so it would line up correctly on the bars. But the problem is. this error: IOError: File not open for reading I did line.readlines() before using the loop. Here's the code by the way.

    def update_thing():
        stud_ID = str(ID_num.get())
        stud_name = str(name.get())
        stud_course = str(Crs.get())
        stud_year = str(Yr.get())
        searchID = str(sID_num.get())
        filename = str(files.get())

        replace = stud_ID +','+ stud_name +','+ stud_course +','+ stud_year
        empty = []



        with open(filename, 'wb') as file:
            Swriter = csv.writer(file, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)
            file.readlines()
            for row in file:
                if row[0:9] == searchID:

                    file.writerow([empty])
                    file.writerow([replace])
                    msg = Label(upd_win, text="Updated Successful", font="fixedsys 12 bold").place(x=3,y=120)

                if not row[0:9] == searchID:
                    msg1 = Label(upd_win, text="Update Failed", font="fixedsys 12 bold").place(x=3,y=120)

Thankyou very much for any help you could offer.

4
  • 3
    A file that's opened only for writing can't be read from. Try with open(filename, 'w+') as file instead. Commented Sep 9, 2017 at 11:23
  • @frederick99 'w+' is the correct mode for a cache file, rarely necessary in the days of large RAM and virtual memory. @Jed Hart does not want to delete all data in the file, and therefore should not use w at all. Commented Sep 9, 2017 at 11:56
  • 2
    Too late to edit my comment now! As phihag pointed out, using 'w+' would overwrite the file with an empty file. Use 'r+' instead. :-) Commented Sep 9, 2017 at 12:39
  • @frederick99 thanks for this fred. because of this I have found the reason why it kept deleting it all haha :) Commented Sep 9, 2017 at 12:49

1 Answer 1

1

The fault is in the line

with open(filename, 'wb') as file:

As documented, open(filename, 'wb') will truncate the file to 0 bytes, i.e. delete all of its contents. In addition, it will be opened write-only.

Instead, open the file with mode 'r+b'. This allows you to read and write, and the file will not get truncated upon opening.

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

Comments

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.