Skip to content Skip to sidebar Skip to footer

Python Command Line Execution

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/arme

Solution 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.

Solution 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 ospath = "/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.

Post a Comment for "Python Command Line Execution"