Results 1 to 3 of 3

Thread: I/O error

  1. #1
    Join Date
    Jan 2012
    Beans
    161

    I/O error

    here is my code :

    Code:
    dbfilename = 'people-file'
    ENDDB = 'enddb.'
    ENDREC = 'endrec.'
    RECSEP = '=>'
    
    def storeDbase(db, dbfilename=dbfilename):
        dbfile = open(dbfilename, 'w')
        for key in db:
            print(key, file=dbfile)
            for(name,value) in db[key].items():
                print(name + RECSEP + repr(value), file=dbfile)
            print(ENDREC, file=dbfile)
            dbfile.close()
    When I try to run this snippet of code I get the traceback that there is an I/O error : Trying to write to closed file????!?!?!?! The lines in bold show where the file is opened, and the last line of bold is where the exception is generated. Any ideas?

  2. #2
    Join Date
    Aug 2010
    Location
    Lancs, United Kingdom
    Beans
    1,588
    Distro
    Ubuntu Mate 16.04 Xenial Xerus

    Re: I/O error

    dbfile.close() is inside the outer for loop. You want it outside that loop. Decrease the indentation on that line so that it matches the open statement.

  3. #3
    Join Date
    May 2007
    Location
    Leeds, UK
    Beans
    1,675
    Distro
    Ubuntu

    Re: I/O error

    In addition, you might also want to look at the "with" statement in Python, which automatically closes a file after a block ends.
    Please create new threads for new questions.
    Please wrap code in code tags using the '#' button or enter it in your post like this: [code]...[/code].

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •