5
\$\begingroup\$

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):
 os.mkdir(dirName)
os.chdir("xml/")
files = []
for file in glob.glob("*.xml"):
 files.append(file)
os.chdir("..")
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?

Peilonrayz
44.4k7 gold badges80 silver badges157 bronze badges
asked May 12, 2019 at 23:59
\$\endgroup\$
1

1 Answer 1

4
\$\begingroup\$
  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.mkdir(dir_name)
os.system(" ".join(
 ["archiver.exe"]
 + ["xml\\" + f for f in glob.glob("xml/*.xml")]
))
answered May 13, 2019 at 13:34
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.