Why does naming the file "con.txt" on Windows force Python to write to the console, not to the file?

I need help debugging the odd behavior of a file in Python. Take the following script ( write_con.py ):

 f=open('con.txt','w') f.write('hi') 

On Linux, this creates a file called con.txt with the contents of hi . On Windows, this writes hi to the console and does not create the file. I tried this with Python 2.5.1, 2.6.3, 2.6.5 and 2.7.2. Execution Example:

 C:\Users\rpsharp> C:\Python27\python.exe .\write_con.py hiC:\Users\rpsharp> C:\Python25\python.exe .\write_con.py hiC:\Users\rpsharp> 

However, a file named nothing but something starting with con works fine ( write_other_con.py ):

 f=open('other_con.txt','w') f.write('hi') 

Here's the run:

 C:\Users\rpsharp> C:\Python25\python.exe .\write_other_con.py C:\Users\rpsharp> type .\other_con.txt hi 

What happens, which leads to the fact that python versions for Windows are written to the console when the prefix of the named con file?

+8
python
source share
4 answers

You should check the Wikipedia file name page . It has a table containing reserved characters for a fairly large number of file systems.

In Windows and DOS utilities, some words can also be reserved and cannot be used as file names. For example, a 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 .

+9
source share

Legacy . In DOS, writing to a file called "CON" writes it to the console; Windows continues this tradition.

+10
source share

This is not a Python error, but a Windows naming convention. A list of reserved keywords that Windows will not allow you to save files or folders, 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.

+5
source share

In Windows con, the word is reserved and cannot be used as a file name.

+1
source share

All Articles