473,804 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Easy question on opening a file

I want to check a directory, see if there are any files in it... then open
each one and do something.

I have this...

files = os.listdir('/direcory')
if len(files) > 0:
for file in files:
f1 = file(file, "r")
do some other stuff

But this raises a TypeError:
TypeError: 'str' object is not callable

So I tried replacing the line f1 = file(file, "r") with f1 = file('%s'
%file, "r")
But that does not work either.

I know this is easy, anyone care to point out the solution.

Thanks.

--
Sean Berry ~ Internet Systems Programmer
BuildingOnline Inc.
The Building Industry's Web Design and Marketing Agency
Celebrating our 9th year in business, founded Aug. 1995
Ph: 888-496-6648 ~ Fax: 949-496-0036
--> Web Design Agency site: http://www.BuildingOnline.net
--> Building Industry Portal: http://www.BuildingOnline.com
--> Building Industry News: http://www.BuildingOnline.com/news/
--> Home Plans: http://www.eHomePlans.com
Jul 18 '05 #1
3 1468

"news.west.cox. net" <se*********@co x.net> wrote in message
news:3_t1d.2964 21$Oi.201894@fe d1read04...
I want to check a directory, see if there are any files in it... then open
each one and do something.

I have this...

files = os.listdir('/direcory')
if len(files) > 0:
for file in files:
f1 = file(file, "r")
do some other stuff
Figured out my mistake already.... 2 minutes later.
I should not be using the word file, which is a python keyword.


But this raises a TypeError:
TypeError: 'str' object is not callable

So I tried replacing the line f1 = file(file, "r") with f1 = file('%s'
%file, "r")
But that does not work either.

I know this is easy, anyone care to point out the solution.

Thanks.

--
Sean Berry ~ Internet Systems Programmer
BuildingOnline Inc.
The Building Industry's Web Design and Marketing Agency
Celebrating our 9th year in business, founded Aug. 1995
Ph: 888-496-6648 ~ Fax: 949-496-0036
--> Web Design Agency site: http://www.BuildingOnline.net
--> Building Industry Portal: http://www.BuildingOnline.com
--> Building Industry News: http://www.BuildingOnline.com/news/
--> Home Plans: http://www.eHomePlans.com

Jul 18 '05 #2
On Mon, 13 Sep 2004 20:57:35 -0700, news.west.cox.n et wrote:
files = os.listdir('/direcory')
if len(files) > 0:
for file in files:
f1 = file(file, "r")
do some other stuff


This will help you:

files = os.listdir('/directory')
print "The name 'file' is bound to:", repr(file)
for file in files:
print "Now the name 'file' is bound to:", repr(file)

(Probably one of the last little warts I get bitten by often is that the
builtins are named a little *too* conveniently... :-) OK, even "wart" is
strong, but you know what I mean.)
Jul 18 '05 #3
news.west.cox.n et <se*********@co x.net> wrote:
...
for file in files:
f1 = file(file, "r")
do some other stuff


Figured out my mistake already.... 2 minutes later.
I should not be using the word file, which is a python keyword.


Not a keyword, or else you would have seen a syntax error as soon as you
tried using it as a normal identifier. Just a built-in name, which
you're perfectly entitle to bind it as an identifier -- but if you do,
of course, then you can't use that same name for two different meanings
in the same scope. In the call 'file(file, ...", the two occurrences of
identifier 'file' MUST refer to the same object.

It's probably best to avoid using Python builtin's names for other
purposes, of course, as you suggest. But there are many such names and
you need not memorize them for the purpose -- if your modules and
functions never use some obscure built-in such as, say, 'apply', there's
no harm done if you use that name as an identifier.

A side note: I think you're opening subdirectories as well as files (or
rather, you''re trying to -- the attempt will probably raise an
exception). You may use a try/except clause to deal with that.
Alex
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3208
by: Hans-Joachim Widmaier | last post by:
Hi all. Handling files is an extremely frequent task in programming, so most programming languages have an abstraction of the basic files offered by the underlying operating system. This is indeed also true for our language of choice, Python. Its file type allows some extraordinary convenient access like: for line in open("blah"): handle_line(line)
5
714
by: PM | last post by:
Has anyone found a way to open a file exclusively where it will fail if the file is already open, i have tried the following _FileStream = new FileStream(@"C:\Data.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None); which does not prevent me from opening the file even if another user has the file open ie Notepad, it will prevent me from saving the file in notepad until i close the file in the app. I can then save changes made in...
4
3093
by: Markus Stoeger | last post by:
Hello! I'm using the FileSystemWatcher to get notified when new files are created in a directory. Once a file appears in the directory I want to read it's contents into memory and do some processing. The problem I'm having is that sometimes the FileSystemWatcher event gets fired before the file is fully written (it gets fired when the file is created.. not when it is created+closed).
14
2472
by: google | last post by:
I am creating a new database for use within our company, that I'd like to make reasonably secure (short of a true server based solution). The back-end of a non-server based database seems to be the biggest security hole, due to the ease of opening, linking, and/or importing raw data directly from the back-end database. I've read information that indicates that locking down the back-end tables to the owner, then using RWOP queries in the...
11
3620
by: aldrin | last post by:
I'm trying to run this code under windows xp sp2 using codeblocks v1.0 compiler with great difficulty.There is no problem with running this under KDevelop in linux. Any help would be greatly appreciated. Enter an interesting string. Too many cooks spoil the broth Error opening C:\myfile.txt for writing. Program termnated. This application has requested the Runtime to terminate it in an unusual way.
7
1818
by: jaysherby | last post by:
Can someone tell me what's the absolute easiest way of putting an image on to the screen in Python without just opening it up in an application? What's the simplest way to just put something up on the screen?
2
5029
by: Craig | last post by:
Hi there, I'm trying to open colour BMPs using PIL and I'm getting the following errors. Opening a 16 colour BMP I get: Traceback (most recent call last): File "<pyshell#3>", line 1, in <module>
8
1996
by: Max Steel | last post by:
Hey gang, I'm new to python coding. I'm trying to find the simplest way to open a text file (on the same server) and display it's content. The text file is plain text (no markup language of any kind). The filename gets found and placed into a variable named I'm using python to find the text files, and a .ezt template to display the list of the files. But I can't figure out how to read the contents of the file, and display it...
34
5375
by: Alexnb | last post by:
Gerhard Häring wrote: No, it didn't work, but it gave me some interesting feedback when I ran it in the shell. Heres what it told me: Traceback (most recent call last): File "<pyshell#10>", line 1, in <module> os.startfile("C:\Documents and Settings\Alex\My Documents\My
0
9704
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9571
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10318
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10302
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6845
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
2
3803
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2976
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.