Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does naming a file 'con.txt' in windows make Python write to console, not file?

Tags:

python

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?

like image 945
Rich Avatar asked Mar 27 '12 18:03

Rich


3 Answers

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

like image 154
Ignacio Vazquez-Abrams Avatar answered Oct 24 '22 05:10

Ignacio Vazquez-Abrams


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.

like image 41
Thanasis Petsas Avatar answered Oct 24 '22 05:10

Thanasis Petsas


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.

like image 44
PenguinCoder Avatar answered Oct 24 '22 07:10

PenguinCoder