473,396 Members | 1,785 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 5286
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.glob('/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**********@hotmail.com> wrote in message
news:ma**************************************@pyth on.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******@jnanqbb.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**********@hotmail.com> wrote in message
news:ma**************************************@pyth on.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(object):
def __init__(self, pathName):
self.dirList = os.listdir(pathName)
self.pathName = pathName
self.dirList.sort()

def walk(self, visitor):
for fileName in self.dirList:
filePath = os.path.join(self.pathName, fileName)
fileStatus = os.stat(filePath)
if stat.S_ISREG(fileStatus.st_mode):
visitor.doFile(filePath, fileStatus)
else:
visitor.doDir(filePath, fileStatus)

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

def doDir(self, dirPath, dirStatus):
DirectoryList(dirPath).walk(cleanDirectory())
os.rmdir(dirPath)

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

def fetchTextFile(inDirPath, fileName):
filePath = os.path.join(inDirPath, fileName)
fileObj = open(filePath, 'rt')
fileList = fileObj.readlines()
fileObj.close()
return fileList

def storeFile(fileText, outNameList, fileStatus):
outFilePath = os.path.join(*outNameList)
outFileObj = open(outFilePath, 'wb')
outFileObj.write(fileText)
outFileObj.close()
os.utime(outFilePath,(fileStatus.st_atime, fileStatus.st_mtime))

def storeTextFile(fileList, outNameList, fileStatus):
outFilePath = os.path.join(*outNameList)
outFileObj = open(outFilePath, 'wt')
outFileObj.writelines(fileList)
outFileObj.close()
os.utime(outFilePath,(fileStatus.st_atime, fileStatus.st_mtime))

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

An example of how to use it is:

----------- MyFileManipulationProgram.py ---------------

# reorganize files captured from the *** web site

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

def setUpOutdir():
DirectoryList("outDir").walk(cleanDirectory())

class copyPicture(object):
def doFile(self, filePath, fileStatus):
head, tail = os.path.split(filePath)
fileText = fetchFile(head, tail)
storeFile(fileText, ("outDir", "pics", tail), fileStatus)

def doDir(self, dirPath, dirStatus):
pass

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

class copyWebPage(object):
def doFile(self, inFilePath, fileStatus):
head, tail = os.path.split(inFilePath)
fileName, extension = os.path.splitext(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(subPattern, "pics", inFileText)

storeFile(inFileText, ("outDir", tail), fileStatus)

def doDir(self, dirPath, dirStatus):
pass

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

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

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

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**********@hotmail.com> wrote in message
news:ma**************************************@pyth on.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
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. ...
10
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...
0
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...
2
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
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...
12
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...
1
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
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...
0
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...
0
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,...

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.