Over the last year, I’ve been working on some automation efforts. I’ve had a few projects lately that involved data-gathering and inventory work. This type of work is very tedious and boring. The exact type of stuff people like to automate. I’ve always been scripting/coding in the background. I remember one of my first computers ever, and the first thing I did with it was to start writing code in Apple BASIC. So I’ve always kept a pulse on programming, but it sways in out and out my work agenda. So with my latest projects I’ve decided to pick it back up.
I’ve had to blow the dust off of some of my old scripts and update some notes. I’m finally getting to a place where I wanted to start sharing some pieces of scripts that I’ve been creating. I’m a proponent of not re-inventing the wheel, but at the same time if I don’t write the code myself I never really grasp what it’s doing. So what I’ve been doing lately has been commenting my code in greater detail so that I can pull out what I need when building a new script.
I started out creating a script that is basically a search+replace function for a CSV file. I created this to help sanitize inventory lists. I had a list of IP addresses and I just wanted to generalize them. I could have accomplished the very same thing manually in Excel with Search+Replace, but then I wouldn’t have built on my scripting skills. Instead I started with a script that opens a CSV file, reads the data and makes changes into an array, and then writes the data into a new CSV file. Those are building blocks I can use to build future scripts. I then went back and added some capability for command-line arguments and input validation. The script itself was more useful as a training excercise than an actual functional tool. I think I’ve used it as a base fore more scripts, than I’ve actually run it as intended.
If you want to take a look at my CSV experiment check it out on GitHub.
Real quick, I want to offer a few tips to help get you started.
1. Don’t re-invent the wheel.
You are not unique and there is a very high chance that what you’re trying to do, someone else has already tried to do and solved. Assimilate that code to help you out.
As you move data through variables and iterations things can get confusing. Also as you deal with variables you will likely run into issues using the wrong variable type, or not knowing what the variable type is being returned by a function you called. To wade your way through this you can use
print(type(x))to print out the type of the variable you are using. So,
Your code can be short, or it can be well understood. Do yourself a favor and comment everything. If coding isn’t your primary job, you’ll need to know why you did something when you pick your script back up in a years time. If you want to re-use something in a future script it will help to know exactly the purpose of snippet of code you developed.