I need help debugging some odd file behavior in Python. Take the following script (write_con.py
):
f=open('con.txt','w')
f.write('hi')
In Linux, this creates a file called con.txt
with the contents hi
. In Windows this writes hi
to the console and does not create a file. I've tried this with Python 2.5.1, 2.6.3, 2.6.5, and 2.7.2. Example run:
C:\Users\rpsharp> C:\Python27\python.exe .\write_con.py
hiC:\Users\rpsharp> C:\Python25\python.exe .\write_con.py
hiC:\Users\rpsharp>
Yet a file named anything other than something that starts with con
works fine (write_other_con.py
):
f=open('other_con.txt','w')
f.write('hi')
Here's a run:
C:\Users\rpsharp> C:\Python25\python.exe .\write_other_con.py
C:\Users\rpsharp> type .\other_con.txt
hi
What's going on that causes windows versions of python to write to the console when the prefix of the named file is con
?
Legacy. In DOS, writing to a file called "CON" writes it to the console instead; Windows continues this tradition.
You have to check the Wikipedia Filename page. It has a table containing the reserved characters for quite a lot of file systems.
In Windows and DOS utilities, some words might also be reserved and can not be used as filenames. For example, DOS Device file:
CON, PRN, AUX, CLOCK$, NUL COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9 LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.
This is not a Python error, but a Windows naming convention. There are a list of reserved keywords that Windows will not allow you to save files or folders as, including CON, PRN, AUX, CLOCK$, NUL
COM0, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT0, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, LPT9.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With