1

I am a Python rookie and I learn Python3.3 in Windows.

I wrote my first script, a script to rename files with incremental filenames. But by now, I had to copy my rename.py script to the directory I want to change the files names and run Python rename.py. It is not a very fancy way to use.

I can improve my code and pass the target directory to run my script in origin directory like Python rename.py .../TargetDir, but I have to copy the directory everytime.

So I want to make my script a system command, then I would only type rename in cmd.exe in the directory I want to rename a bunch of files. How can I approach this.

1
  • Instead of passing the target directory as an argument, you can simply use os.getcwd() (assuming the working directory does not change before this function is executed). Commented Aug 21, 2014 at 1:12

2 Answers 2

2

For this purpose, you'll want to use doskey, which allows you to set aliases for commands.

You use it like this:

doskey macroName=macroDefinition

So you would want to write something like this:

doskey rename=Python rename.py .

Where the . stands for the directory you're currently in. (I wasn't exactly clear on what you wanted -- the way I read your question was that you just want to cd into the directory where you want to rename a bunch of files, then run the script.)

Sign up to request clarification or add additional context in comments.

Comments

1

Use sys.argv to get the command line arguments. For example test.py:

import os
import sys

path = sys.argv[1]
print(os.listdir(path))

and then you can create a batch file which should placed in a folder that belongs to the PATH variable. In order to do so, create a text document with the following contents and save it as ListDir.bat. Copy the ListDir.bat to either your python folder, or Windows folder (both should be in your PATH)

ListDir.bat:

python C:\test.py "%CD%"
PAUSE

The %CD% refers to the current directory in the windows prompt. So assuming the python script test.py is in C:\ the first line executes the test.py script with the argument current directory.

I used PAUSE to get user input before completing the script, you could choose not to.

After you save the ListDir.bat file. You can navigate to the folder you want to use it in, and just call ListDir

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.