473,738 Members | 5,084 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Python Script for Running a Python Program over Different Files inthe Directory

Hey,

Can anyone give me a snippet for running a python program over all the files
in the directory.
For ex: I have ten files in a directory and I want to run a python program
against all of these files, I wish to do the same using another python code
instead of running each of these files one by one, which would be cumbersome
giving the argv of each file every single time.

This can be easily done using a shell script but I just wanted to have a
flavour of python for this.

Thanks
Shalen

_______________ _______________ _______________ _______________ _____
Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1!
(Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/
Jul 18 '05 #1
5 5324
something like:

import os

for f in os.listdir('/path/to/dir'):
<do stuff to f>

that's the best way i know for doing something to each file in a directory...

On Sat, 13 Mar 2004 08:22:09 +0000, Shalen chhabra wrote:
Hey,

Can anyone give me a snippet for running a python program over all the files
in the directory.
For ex: I have ten files in a directory and I want to run a python program
against all of these files, I wish to do the same using another python code
instead of running each of these files one by one, which would be cumbersome
giving the argv of each file every single time.

This can be easily done using a shell script but I just wanted to have a
flavour of python for this.

Thanks
Shalen

_______________ _______________ _______________ _______________ _____
Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1!
(Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/


Jul 18 '05 #2
Ivo
import glob,os
filelist=glob.g lob('/folder here/*') # retrieve your listing.
for file in filelist:
if os.path.isfile( file):
<do your stuff here>
--
Cheerz,
Ivo.
http://IvoNet.nl
=============== =============
"Shalen chhabra" <sh**********@h otmail.com> wrote in message
news:ma******** *************** *************** @python.org...
Hey,

Can anyone give me a snippet for running a python program over all the files in the directory.
For ex: I have ten files in a directory and I want to run a python program against all of these files, I wish to do the same using another python code instead of running each of these files one by one, which would be cumbersome giving the argv of each file every single time.

This can be easily done using a shell script but I just wanted to have a
flavour of python for this.

Thanks
Shalen

_______________ _______________ _______________ _______________ _____
Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1!
(Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/

Jul 18 '05 #3
Shalen chhabra wrote on Sat, 13 Mar 2004 08:22:09 +0000:
Can anyone give me a snippet for running a python program over all the files
in the directory.


You can use os.listdir() to get all files in a given path as a list. Then
you can loop over that list and do whatever you like to each item in that
list.

--
Yours,

Andrei

=====
Real contact info (decode with rot13):
ce******@jnanqb b.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
Jul 18 '05 #4

"Shalen chhabra" <sh**********@h otmail.com> wrote in message
news:ma******** *************** *************** @python.org...
Hey,

Can anyone give me a snippet for running a python program over all the files in the directory.
For ex: I have ten files in a directory and I want to run a python program against all of these files, I wish to do the same using another python code instead of running each of these files one by one, which would be cumbersome giving the argv of each file every single time.

This can be easily done using a shell script but I just wanted to have a
flavour of python for this.
Given your reply to the attempts to help, I'm going to
assume that what you want is to separate the actual manipulation
of each file from the logic of determining which files to manipulate.

If this isn't what you want, please stop reading now and don't
bother to reply - it'll save both of us aggrivation.

The answer to the problem is the visitor pattern. It's a
standard pattern (see "Design Patterns" [GOF].)

The directory program is:

---------- DirBase.py ------------------------
# Basic classes for file maintenance

import os, stat, os.path

class DirectoryList(o bject):
def __init__(self, pathName):
self.dirList = os.listdir(path Name)
self.pathName = pathName
self.dirList.so rt()

def walk(self, visitor):
for fileName in self.dirList:
filePath = os.path.join(se lf.pathName, fileName)
fileStatus = os.stat(filePat h)
if stat.S_ISREG(fi leStatus.st_mod e):
visitor.doFile( filePath, fileStatus)
else:
visitor.doDir(f ilePath, fileStatus)

class cleanDirectory( object):
def doFile(self, filePath, fileStatus):
os.remove(fileP ath)

def doDir(self, dirPath, dirStatus):
DirectoryList(d irPath).walk(cl eanDirectory())
os.rmdir(dirPat h)

def fetchFile(inDir Path, fileName):
filePath = os.path.join(in DirPath, fileName)
fileObj = open(filePath, 'rb')
fileText = fileObj.read()
fileObj.close()
return fileText

def fetchTextFile(i nDirPath, fileName):
filePath = os.path.join(in DirPath, fileName)
fileObj = open(filePath, 'rt')
fileList = fileObj.readlin es()
fileObj.close()
return fileList

def storeFile(fileT ext, outNameList, fileStatus):
outFilePath = os.path.join(*o utNameList)
outFileObj = open(outFilePat h, 'wb')
outFileObj.writ e(fileText)
outFileObj.clos e()
os.utime(outFil ePath,(fileStat us.st_atime, fileStatus.st_m time))

def storeTextFile(f ileList, outNameList, fileStatus):
outFilePath = os.path.join(*o utNameList)
outFileObj = open(outFilePat h, 'wt')
outFileObj.writ elines(fileList )
outFileObj.clos e()
os.utime(outFil ePath,(fileStat us.st_atime, fileStatus.st_m time))

------------------------------------------------------------

An example of how to use it is:

----------- MyFileManipulat ionProgram.py ---------------

# reorganize files captured from the *** web site

import os, stat, os.path
import re
from DirBase import *

def setUpOutdir():
DirectoryList(" outDir").walk(c leanDirectory() )

class copyPicture(obj ect):
def doFile(self, filePath, fileStatus):
head, tail = os.path.split(f ilePath)
fileText = fetchFile(head, tail)
storeFile(fileT ext, ("outDir", "pics", tail), fileStatus)

def doDir(self, dirPath, dirStatus):
pass

# precompile patterns used for multiple files
script = re.compile(r"<s cript>.*?</script>")
meta = re.compile(r"<M ETA.*?>")
cmnt = re.compile(r"<\ !--.*?-->")
cmnt1 = re.compile(r"<\ !--//-->")
html = re.compile(r"\. html")

class copyWebPage(obj ect):
def doFile(self, inFilePath, fileStatus):
head, tail = os.path.split(i nFilePath)
fileName, extension = os.path.splitex t(tail)
inFileText = fetchFile(head, tail)
print ("path: '%s' head: '%s' tail: '%s' name: '%s' ext: '%s'\n" %
(inFilePath, head, tail, fileName, extension))
if extension == ".htm":
inFileText = script.sub("", inFileText)
#inFileText = meta.sub("", inFileText)
inFileText = cmnt1.sub("", inFileText)
inFileText = html.sub(".htm" , inFileText)
subPattern = "%s_files" % tail[:-4]
inFileText = re.sub(subPatte rn, "pics", inFileText)

storeFile(inFil eText, ("outDir", tail), fileStatus)

def doDir(self, dirPath, dirStatus):
pass

def main(inDirPath) :
DirectoryList(i nDirPath).walk( copyWebPage())

if __name__ == "__main__":
setUpOutdir()
main(r"c:\mydir ectory")

----------------------------------------------------------------------

I have any number of file fixup programs that use the
same DirBase.py program.

HTH

John Roth
Thanks
Shalen

Jul 18 '05 #5
Ivo
look at the execfile( filename[, globals[, locals]])

command in de manpages

or the following
execl( path, arg0, arg1, ...)

execle( path, arg0, arg1, ..., env)

execlp( file, arg0, arg1, ...)

execlpe( file, arg0, arg1, ..., env)

execv( path, args)

execve( path, args, env)

execvp( file, args)

execvpe( file, args, env)
Use the other examples to iterate
--
Cheerz,
Ivo.
http://IvoNet.nl
=============== =============
"Shalen chhabra" <sh**********@h otmail.com> wrote in message
news:ma******** *************** *************** @python.org...
Hey,

Can anyone give me a snippet for running a python program over all the files in the directory.
For ex: I have ten files in a directory and I want to run a python program against all of these files, I wish to do the same using another python code instead of running each of these files one by one, which would be cumbersome giving the argv of each file every single time.

This can be easily done using a shell script but I just wanted to have a
flavour of python for this.

Thanks
Shalen

_______________ _______________ _______________ _______________ _____
Fast. Reliable. Get MSN 9 Dial-up - 3 months for the price of 1!
(Limited-time Offer) http://click.atdmt.com/AVE/go/onm00200361ave/direct/01/

Jul 18 '05 #6

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

Similar topics

10
3689
by: Andrew Dalke | last post by:
Is there an author index for the new version of the Python cookbook? As a contributor I got my comp version delivered today and my ego wanted some gratification. I couldn't find my entries. Andrew dalke@dalkescientific.com
10
9922
by: TokiDoki | last post by:
Hello there, I have been programming python for a little while, now. But as I am beginning to do more complex stuff, I am running into small organization problems. It is possible that what I want to obtain is not possible, but I would like the advice of more experienced python programmers. I am writing a relatively complex program in python that has now around 40 files.
0
1569
by: Fuzzyman | last post by:
It's finally happened, `Movable Python <http://www.voidspace.org.uk/python/movpy/>`_ is finally released. Versions for Python 2.3 & 2.4 are available from `The Movable Python Shop <http://voidspace.tradebit.com/groups.php>`_. The cost is £5 per distribution, payment by PayPal. £1 from every distribution goes to support the development of `SPE <http://pythonide.stani.be/>`_, the Python IDE.
2
1646
by: arvind | last post by:
When I run the script on server,only HTML part gets executed. But the python code appears as it is on the screen in the text format. How to run the CGI script on web server using Python2.4.3?
34
3965
by: Ben Sizer | last post by:
I've installed several different versions of Python across several different versions of MS Windows, and not a single time was the Python directory or the Scripts subdirectory added to the PATH environment variable. Every time, I've had to go through and add this by hand, to have something resembling a usable Python installation. No such problems on Linux, whether it be Mandrake/Mandriva, Fedora Core, or Kubuntu. So why is the Windows...
12
3014
by: adamurbas | last post by:
ya so im pretty much a newb to this whole python thing... its pretty cool but i just started today and im already having trouble. i started to use a tutorial that i found somewhere and i followed the instructions and couldnt get the correct results. heres the code stuff... temperature=input("what is the temperature of the spam?") if temperature>50: print "the salad is properly cooked." else:
1
47476
KevinADC
by: KevinADC | last post by:
Note: You may skip to the end of the article if all you want is the perl code. Introduction Many websites have a form or a link you can use to download a file. You click a form button or click on a link and after a moment or two a file download dialog box pops-up in your web browser and prompts you for some instructions, such as “open” or “save“. I’m going to show you how to do that using a perl script. What You Need Any recent...
0
8968
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
9334
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
9259
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
9208
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...
0
8208
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6053
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();...
1
3279
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2744
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2193
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.