Saving to Text Files Through the Command Line (A Python Shortcut)
As I near the end of my Automate the Boring Stuff course, I’m learning some very useful tools - especially as a Windows user. In order to synthesize my learning, I decided to do a little project combining a few new python functionalities I learned including:
· Running python scripts from the command line
· The pyperclip module
· Opening and editing files
The final result is a program that will take any block of text you’ve copied and automatically save it as a text file in a preset folder with a few keyboard taps.
Perhaps you are wondering why this is useful. Here is a quick table comparing the normal set of steps versus the new set:
Step Number | Old Way | New Way |
---|---|---|
1 | Select the text you want to save. | Select the text you want to save. |
2 | Ctrl + C | Ctrl + C |
3 | Open Notepad | Ctrl + R |
4 | Ctrl + V | Type: savetotxt filename |
5 | Ctrl + S | |
6 | Type in filename |
Not only are there fewer steps, but there are also additional time savings from waiting for programs to open and close etc.
How to create this for yourself
Step 1: Set up your command line PATH
This is so that you don’t have to write out the full path to your script every time you’d like to run it (i.e. you just need to write ‘savetotext’ in the run dialogue instead of ‘C:\users\salim\projects\savetotext.py’).
Go to Control Panel > System > Advanced System Settings
In the Advanced tab, click on Environment Variables…
Then in the variable “Path”, add the directory you want it to pull from.
Step 2: Create the .bat file for your code
This is so that your code can actually be executable from the command line.
· Create a file in your python editor.
· Type in the following code:
@pyw C:\[the file path you set in step 1]\savetotext.py %*
· Save this file as savetotext.bat
Step 3: Write the code
import sys #so it can run from the command line
import pyperclip #so it can access your clipboard
text = pyperclip.paste() #saves what's in your clipboard
filename = '-'.join(sys.argv[1:]) #saves what's in your clipboard
saveFile = open('C:\\Users\\salim\\projects\\saved texts\\' + filename +'.txt','w') #creates the text file in your preset folder
saveFile.write(text) #pastes in the text from your clipboard
saveFile.close() #closes the file so it doesn't keep running
And that’s it! I’d love to hear if you’ve tried it out or can think of other programs that can be created in a similar way.
Also, do you want to be notified of my blog post and my other updates once a month? Subscribe to my free substack newsletter 5 on the 9.
See you next month!