Skip to content

Allow mode='x' even for Python < 3.3#94

Merged
mgeier merged 1 commit intomasterfrom
emulate-x
Nov 27, 2014
Merged

Allow mode='x' even for Python < 3.3#94
mgeier merged 1 commit intomasterfrom
emulate-x

Conversation

@mgeier
Copy link
Contributor

@mgeier mgeier commented Nov 27, 2014

For #77 it would be very helpful if mode='x' were supported for all Python versions, not only >= 3.3.

In this PR I tried to implement mode='x' "manually" by checking if a file exists before opening it and not by relying on the built-in open() function.
The main point is that SFM_RDWR doesn't truncate an existing file, but this would be expected from mode='w+'.
As a work-around, the file is first opened with os.open() using the os.O_TRUNC flag to truncate the file, then immediately closed and opened again with libsndfile in SFM_RDWR mode.
This only works when specifying a file name, it doesn't work for file descriptors and file-like objects. Those have to be truncated already before using them in SoundFile.

This is basically an alternative implementation for #65 (but hopefully better).
It is a combination of point 1 and 3 in #59.
It should have the same behavior as discussed in #60, but with a different implementation.

Along the way, it would automatically solve most of #68.

The built-in open() function isn't used anymore.
The function os.path.isfile() is used to check if a file exists already.
For mode 'w+', an existing file is first opened in write-only mode to
make sure it is truncated. Afterwards it is re-opened in read/write
mode.
@bastibe bastibe added this to the 0.6.0 milestone Nov 27, 2014
@bastibe
Copy link
Owner

bastibe commented Nov 27, 2014

Great work!

mgeier added a commit that referenced this pull request Nov 27, 2014
Allow mode='x' even for Python < 3.3
@mgeier mgeier merged commit 9d9b734 into master Nov 27, 2014
@mgeier mgeier deleted the emulate-x branch November 27, 2014 16:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants