How to ensure a file is closed for writing in Python? -


the issue described here looked solvable having spreadsheet closed in excel before running program.

it transpires, however, having excel closed necessary, not sufficient, condition. issue still occurs, not on every windows machine, , not every time (sometimes occurs after single execution, two).

i've modified program such reads 1 spreadsheet , writes different one, still issue presents itself. go on programmatically kill lingering python processes before running program. still no joy.

the openpyxl save() function instantiates zipfile thus:

archive = zipfile(filename, 'w', zip_deflated, allowzip64=true) 

... zipfile using attempt open file in mode 'wb' thus:

if isinstance(file, basestring):     self._filepassed = 0     self.filename = file     modedict = {'r' : 'rb', 'w': 'wb', 'a' : 'r+b'}     try:         self.fp = open(file, modedict[mode])     except ioerror:         if mode == 'a':             mode = key = 'w'             self.fp = open(file, modedict[mode])         else:             raise 

according the docs:

on windows, 'b' appended mode opens file in binary mode, there modes 'rb', 'wb', , 'r+b'. python on windows makes distinction between text , binary files; end-of-line characters in text files automatically altered when data read or written. behind-the-scenes modification file data fine ascii text files, it’ll corrupt binary data in jpeg or exe files. careful use binary mode when reading , writing such files. on unix, doesn’t hurt append 'b' mode, can use platform-independently binary files.

... explains why mode 'wb' must used.

is there in python file opening possibly leave file in state of "openness"?

windows: 8

python: 2.7.10

openpyxl: latest

two suggestions:

first use with close file correctly.

with open("some.xls", "wb") excel_file:     #do 

at end of file close on own (see this).

you can make copy of file , work on copied file.

import shutil shutil.copyfile(src, dst) 

https://docs.python.org/2/library/shutil.html#shutil.copyfile


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -