I have a directory and I want to pick every file within that directory and run a python code on it: So I do the following
for file in os.listdir('/Users/Desktop/Xfiles'):
os.system('/sw/bin/python2.7 pythonCode.py /Users/Desktop/Xfiles/file')
This does not work, I want to process the "file" from the listdir....how can I do that?
The path passed to the os.system
is hard coded. You should pass filename
.
dirpath = '/Users/Desktop/Xfiles'
for filename in os.listdir(dirpath):
os.system('/sw/bin/python2.7 pythonCode.py {}/{}'.format(dirpath, filename))
file
as variable name. It shadows builtin file
function. You can do string interpolation with
file = "myfilename"
"some text {}".format(file)
# white should result in "some text myfilename"
But for manipulating paths, the best way is to use
os.path.join('/Users/gchella1/Desktop/forGeorge/Xfiles/', file)
did you forget to put "file" out of the quotes ?
for file in os.listdir('/Users/gchella1/Desktop/forGeorge/Xfiles'):
os.system('/sw/bin/python2.7 pythonCode.py /Users/gchella1/Desktop/forGeorge/Xfiles/'+file)
this works for me.
for file in os.listdir('.'):
os.system('ls '+file)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.