How to write Scripts in Python
Performing a repetitive task manually can be extremely tedious, so it is preferable to automate it. Using Python, a versatile and powerful programming language, we can easily write a script to handle the automation.
For example, let’s say we have many files scattered across your desktop, and we need to organize them neatly into folders. Instead of dragging and dropping each file one by one, we can write a Python script to do it for us.
In this tutorial, we’ll show you how to write, run, and debug scripts in Python.
If you’re not familiar with Python, check out Codecademy’s Python course.
What is Scripting in Python?
Scripting involves writing small programs that automate repetitive tasks. Scripts can perform a variety of functions and are typically written in languages that are interpreted rather than compiled such as Python.
Think of it as teaching our computer to do tasks automatically. Whether it’s sorting files, crunching numbers, or even sending emails, we can write a Python script for it.
Scripting vs programming vs coding
We are using Python to write the scripts. How is this different from programming?
Here is a detailed breakdown of the differences between programming and scripting:
Scripting | Programming | Coding | |
---|---|---|---|
Definition | Writing scripts to automate tasks | Developing complete applications | Writing code in any language |
Execution | Interpreted | Compiled or interpreted | Can be either compiled or interpreted |
Complexity | Generally simpler, task-specific | More complex, often larger scale | Varies, from simple scripts to complex apps |
Use Cases | Automation, web dev, data analysis | Full-fledged software development | Any task that requires code |
Examples | Python, JavaScript, Bash | C++, Java, Python | Any programming or scripting language |
Basic Scripting Operations
Now, let’s learn how to write and run basic Python scripts.
Writing a Python script
Let’s write a Python script to automate the process of renaming multiple files in a directory as an example. The script will allow us to specify a directory that contains the files to be renamed and a common prefix to prepend to each file name.
Suppose a file has the name file 1
, after running the script, it’ll change to old_file1
as the prefix defined is old
.
Let’s create a file called scripting.py
and write the code in this file.
First, import the os
module to help us interact with the operating system.
Import os
Next, we’ll write a rename_files()
function to rename the files. It’ll iterate through each file in the directory and check if it’s a regular file (not a directory) using the os.path.isfile()
function.
We’ll use os.path.splitext()
function to split the file name and extension. We’ll then construct the new file name with the specified prefix, rename the file using os.rename()
function.
def rename_files(directory, prefix):# Change directory to the specified pathos.chdir(directory)# List all files in the directoryfiles = os.listdir()# Iterate through each file and rename itfor file in files:# Check if the file is a regular file (not a directory)if os.path.isfile(file):# Split the file name and extensionfilename, file_extension = os.path.splitext(file)# Construct the new file name with the specified prefixnew_filename = f"{prefix}_{filename}{file_extension}"# Rename the fileos.rename(file, new_filename)# Print a message indicating the file has been renamedprint(f"Renamed {file} to {new_filename}")
We’ll define the directory (\Folder
) to be used and the prefix old
in the main()
function:
def main():# Specify the directory containing the files to be renameddirectory = "\Folder"# Specify the prefix to prepend to each file nameprefix = "old"# Rename files in the specified directory with the specified prefixrename_files(directory, prefix)if __name__ == "__main__":main()
The code to automate the renaming process is ready. Let’s learn how to run this Python script.
Note: Replace the path to the directory. We want to change the file names of the
\Folder
folder so we’ve defined thedirectory
variable with the correct path.
Running a Python Script
We use the following syntax in a command line to run a script in Python:
python fileName.py
To run our script, open the command line interface or terminal, write this command, and press Enter:
python scripting.py
Debugging a Python Script
Debugging is an essential skill for any programmer, and Python offers several tools and techniques to help you identify and fix errors in your scripts.
- Print Statements
One of the simplest debugging techniques is to insert print statements throughout the script to display the values of variables and the flow of execution.
- Using a Debugger
Python’s built-in debugger, pdb
, lets us step through the code and inspect variables interactively. You can run this script with pdb
by executing:
python -m pdb your_script.py
We can use these commands to interact with the debugger:
n
(next): Execute the current line and move to the next line of code.s
(step): Step into the function call on the current line.c
(continue): Continue execution until the next breakpoint is reached.l
(list): Display the current line of code and surrounding lines.p
(print): Print the value of a variable.q
(quit): Quit the debugger and terminate the script.
We can use these commands to interact with the debugger.
- Logging
Python’s logging module allows us to log messages at different levels of severity, which can help us track the execution of our script and diagnose issues.
Wrapping Up
In this tutorial, we covered:
- Scripting simplifies and automates tasks.
- It is task-specific, while programming involves creating complete applications.
- You can use the
.py
file extension for the scripts and run them usingpython fileName.py
command.
Try implementing the concepts you learned and write your own scripts in Python. Here are some ideas to work on:
- A script that counts the number of words in a text file.
- A script that generates a random number and prompts the user to guess it.
- A script that displays a random quote from a predefined list of quotes.
Author
'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'
Meet the full teamRelated articles
Learn more on Codecademy
- Skill path
Code Foundations
Start your programming journey with an introduction to the world of code and basic concepts.Includes 5 CoursesWith CertificateBeginner Friendly4 hours - Career path
Full-Stack Engineer
A full-stack engineer can get a project done from start to finish, back-end to front-end.Includes 51 CoursesWith Professional CertificationBeginner Friendly150 hours