os.rename on Windows

Chris Angelico rosuav at gmail.com
Wed Mar 23 08:27:41 EDT 2016


On Wed, Mar 23, 2016 at 11:17 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> import os
> open('a123.junk', 'w')
> open('b123.junk', 'w')
> try:
>     os.rename('a123.junk', 'b123.junk')
> except OSError as e:
>     print(e.winerror)  # Windows only
>     print(e.errno)
>     print(repr(e))
>
> os.unlink('a123.junk')
> os.unlink('b123.junk')
>

32-bit Python on 64-bit Windows 7 in a VirtualBox VM under Debian Testing.

Python 3.5.1 (v3.5.1:37a07cee5969, Dec  6 2015, 01:38:48) [MSC v.1900 32 bit (In
tel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> open('a123.junk', 'w')
<_io.TextIOWrapper name='a123.junk' mode='w' encoding='cp1252'>
>>> open('b123.junk', 'w')
<_io.TextIOWrapper name='b123.junk' mode='w' encoding='cp1252'>
>>> try:
...     os.rename('a123.junk', 'b123.junk')
... except OSError as e:
...     print(e.winerror)  # Windows only
...     print(e.errno)
...     print(repr(e))
...
183
17
FileExistsError(17, 'Cannot create a file when that file already exists')
>>> os.unlink('a123.junk')
>>> os.unlink('b123.junk')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
PermissionError: [WinError 32] The process cannot access the file because it is
being used by another process: 'b123.junk'
>>>


The last error is because _ is retaining the open file, so it hasn't
been closed. Entering any non-None expression allows the unlink.

ChrisA



More information about the Python-list mailing list