8

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?

Rich
  • 11,049
  • 9
  • 58
  • 91

4 Answers4

10

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

Ignacio Vazquez-Abrams
  • 740,318
  • 145
  • 1,296
  • 1,325
9

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.

Thanasis Petsas
  • 4,218
  • 5
  • 30
  • 56
5

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.

PenguinCoder
  • 4,264
  • 1
  • 25
  • 37
1

In Windows con is reserved word and can not be used as filename.

Wilduck
  • 13,388
  • 10
  • 56
  • 89
Computer_Engineer
  • 343
  • 1
  • 8
  • 19