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)
-
How many PDF files are in that directory? That shell command should fail if there is more than one.Keith– Keith2011年09月05日 09:45:43 +00:00Commented Sep 5, 2011 at 9:45
-
Your right. There was only one pdf at the time when I was trying out the command. but realized that renaming will fail for more than one and started trying out moving all the pdfs to another directory.Amritha– Amritha2011年09月05日 15:35:36 +00:00Commented Sep 5, 2011 at 15:35
2 Answers 2
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 Comments
glob.glob() returns a list. You must integrate it into the list you pass to subprocess.call().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.