\$\begingroup\$
\$\endgroup\$
1
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?
-
\$\begingroup\$ Hi nansy. This post is being discussed on meta: codereview.meta.stackexchange.com/questions/9165/… \$\endgroup\$rolfl– rolfl2019年05月14日 15:00:36 +00:00Commented May 14, 2019 at 15:00
1 Answer 1
\$\begingroup\$
\$\endgroup\$
- Looping over
glob.glob
to build files is unneeded. - You shouldn't need to
chdir
if you change the glob toxml/*.xml
filearchiver_cmdline
can be changed to usestr.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
lang-py