问题
I am trying to rename a set of pdf files in my desktop using a simple python script. I am somehow not very successful. My current code is :
import os,subprocess
path = "/Users/armed/Desktop/"
for file in os.listdir(path)
command = ['mv', '*.pdf' , 'test.pdf'] // mv Command to rename files to test.pdf
subprocess.call(command)
The output i get for this code is 1 and the files are not renamed. The same command works when executed in the terminal. I am using a Mac (if that helps in any way)
回答1:
The same command works when executed in the terminal.
Except it's not the same command. The code is running:
'mv' '*.pdf' 'test.pdf'
but when you type it out it runs:
'mv' *.pdf 'test.pdf'
The difference is that the shell globs the *
wildcard before executing mv
. You can simulate what it does by using the glob module.
回答2:
Python is not going to expand the shell wildcard in the string by default. You can also do this without a subprocess. But your code will lose all pdf files except the last one.
from glob import glob
import os
path = "/Users/armed/Desktop/"
os.chdir(path)
for filename in glob("*.pdf"):
os.rename(filename, "test.pdf")
But I'm sure that's not what you really want. You'll need a better destination name.
来源:https://stackoverflow.com/questions/7306178/python-command-line-execution