[Tutor] Opening files - Newbie Question

Rob Andrews rob@jam.rr.com
Tue, 17 Jul 2001 15:47:11 -0500


I've tried to reproduce your situation a bit. Here's what I found. I saved
the code from your email into a file Untitled.py and as Bruce.txt in
D:\Python21\ (Windows box).

In PythonWin, the following occured when I ran Untitled.py

>>> import Untitled

# A separate window opened prompting me to 'Enter file name: ' and I tried
'Bruce' with no success, and 'D:\Python21\Bruce' with similar results (shown
here):

Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "d:\python21\Untitled.py", line 2, in ?
    file = open(filename, 'r')
IOError: [Errno 2] No such file or directory: 'D:\\Python21\\Bruce'

>>> import Untitled
>>> reload(Untitled)

# Success this time, as I entered 'D:\Python21\Bruce.txt' and saw its
contents printed here.

filename = raw_input('Enter file name: ')

file = open(filename, 'r')

allLines = file.readlines()

file.close()

for eachLine in allLines:

    print eachLine
<module 'Untitled' from 'd:\python21\Untitled.pyc'>

# But when I tried to open a GIF image file, it failed, as shown below. But
this didn't surprise me too much, because your code specified line-by-line
reading, which implied text to me.

>>> import Untitled
>>> reload(Untitled)
GIF89aJ<module 'Untitled' from 'd:\python21\Untitled.pyc'>
>>>

No matter whether you're using Windows or not (or IDLE versus PythonWin),
I'd expect you to get similar results.

hopefully helpful,
Rob

"Perl is worse than Python because people wanted it worse." Larry Wall
(Creator of Perl), 14 Oct 1998
Useless Python: http://www.lowerstandard.com/python/

# -----Original Message-----
# From: tutor-admin@python.org [mailto:tutor-admin@python.org]On Behalf Of
# DavidCraig@PIA.CA.GOV
# Sent: Tuesday, July 17, 2001 3:28 PM
# To: tutor@python.org
# Subject: [Tutor] Opening files - Newbie Question
#
#
# Example from  Wes Chun's 'Core Python Programming' page 38:
#
#
# # Open files to window to read
#
# filename = raw_input('Enter file name: ')
# file = open(filename, 'r')
# allLines = file.readlines()
# file.close()
# for eachLine in allLines:
#     print eachLine
#
# When I run the file and enter a text file to be read I get:
#
# Python 2.1 (#15, Apr 16 2001, 18:25:49) [MSC 32 bit (Intel)] on win32
# Type "copyright", "credits" or "license" for more information.
# IDLE 0.8 -- press F1 for help
# >>>
# Enter file name: bruce
# Traceback (most recent call last):
#   File "C:/Python21/Practice/File_open.py", line 4, in ?
#     file = open(filename, 'r')
# IOError: [Errno 2] No such file or directory: 'bruce'
#
# What am I missing?  I have tried to input the exact path.  Must
# the file be
# a text file to be read?
#
# Thanks for any help.
#
# D. H. Craig, CSM
#
#
#
# _______________________________________________
# Tutor maillist  -  Tutor@python.org
# http://mail.python.org/mailman/listinfo/tutor