[Tutor] need help opening a file in idle

Alan Gauld alan.gauld at btinternet.com
Sun May 24 10:16:33 CEST 2009

"Meital Amitai" <meital.amitai at gmail.com> wrote

> I am not sure how to open a file in my computer in idle.

You need to be clear what you are doing. You are not
opening the file in IDLE you are opening the file in Python.
IDLE is just the tool you use to write Ptython programs.

> For my python class the homework states to write a function that accepts 
> the
> name of a file and returns a tuple containing the number of lines, words 
> and
> characters in the file. My problem is how do I get idle to first accept 
> the
> name of a file.

You need to get Python to accept the name of the file.
And the biggest problem there is to identify the full path
of the file. To program successfully you will need to understand
where and how your computer stores files. On modern computers casual
users don't really need to know that kind of stuff but programmers do.

> I created a file in text edit program saved with a .doc
> extension, saved on my desktop. However the only way I have learned to 
> open
> a file in my class is to write something like:
> f = open('inputfile','r')
> line = f.readline()

> but when i type exactly that into my idle i get the following error 
> message:
> Traceback (most recent call last):
>  File "<pyshell#12>", line 1, in <module>
>    f = open('inputfile','r')
> IOError: [Errno 2] No such file or directory: 'inputfile'

I'm assuming you realise that inputfile is a symbol that stands for
any file name it doesn't have to be literally inputfile... But the file
must exist before you can read it (the 'r' bit says you want to
read the file)

> and when i ask it to open the actual file i created in my text edit 
> program:
> file1.doc
> f = open('file1.doc','r')
> I get the same message.

You didn't tell Python to look in the Desktop folder
(Although that's not a good place to store files unless
you want a very confusing desktop! You would be better
to store it in MyDocuments)

> I am not sure how to tell it to go to desktop folder in my computer where 
> i
> saved that file. Am I missing something, and completely not getting the
> point?

It's up to you to know where the file is and tell Python.

You might try this to find out where Python is looking for
the file by default.

import os
print os.getcwd()

Which prints what Python considers the Current Working Directory.

You will find a lot more on this topic, including a program for
counting words in a file in the Handling files topic of my tutorial.


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list