3 Ways to Create a Pile o’ Files

Earlier this week, I needed to create 100 files, 001–100. Being a programmer, I obviously wouldn’t do this manually. Here are three programmatic ways I could have done this task.

Drill: multifunction. Impact driver: amazing at limited things. Screwdriver: does what it says it will.

First, I figured I should try it in Python, because that’s what I am currently learning. Here’s what I came up with:

for i in range(1, 101):
i = (‘%03i’ % i)
open(i + ‘.py’, ‘w’)

That works! But Python’s range did not work exactly like I wanted. It can only include integers, so I had to convert the integer to a string before I create the file. Also, range is exclusive (stops before the second parameter), which meant I had to write 101 even though there will be no 101.py.

Next, I conjured up a Ruby script, since that’s the language I’ve spent the most time in. Since Ruby is known for being flexible, I’m sure there are other ways, but my block-loving self wrote:

(“001”..”100").each do |number|
File.new(“#{number}.rb”, “w+”)

You’ll notice that Ruby’s range is clever enough to automatically increment on strings. Also, since I used two dots, I could make it inclusive (no 101 confusion here).

Finally, I decided to experiment around with writing it as a shell script. When I was first determining how to do this, I discovered a a neat bash feature called brace expansion, which al me the oneliner:

touch {1..100}.sh

However, that ignored my leading zeroes, so once again, I had to turn to a for loop with some formatting trickery:

for (( num=1; num<=100; num++ ))
touch `printf “%03d” $num`.sh

What have we learned from this? Nothing that we couldn’t have anticipated. Bash is powerful but inflexible (impact driver). Ruby is flexible and can do magic tricks (power drill). Python is exacting but predictable (screwdriver). And ultimately, a big part of programming is figuring out what tool you actually need for the job.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.