I have a program that needs to run an command on all the files in a folder:

import glob
import os

dirName = "../pack"

if not os.path.exists(dirName):


files = []
for file in glob.glob("*.xml"):


filearchiver_cmdline = "archiver.exe"

for myFile in files:
    filearchiver_cmdline += " xml\\" + myFile

os.system( filearchiver_cmdline )

The command should look like this:

Arhiver.exe file1.xml

What should I change / optimize for this code? Would a class be needed? Should there be logical def-s? Are the variables name good?

  1. Looping over glob.glob to build files is unneeded.
  2. You shouldn't need to chdir if you change the glob to xml/*.xml
  3. filearchiver_cmdline can be changed to use str.join and a comprehension.

Note: untested

import glob
import os

dir_name = "../pack"

if not os.path.exists(dir_name):

os.system(" ".join(
    + ["xml\\" + f for f in glob.glob("xml/*.xml")]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.