top of page

10.06.2018: One Lesson of Coding


Today's soundtrack is Elder: Lore, a recently-released but classic-sounding heavy metal album. I love its artwork.


This morning, I'm beginning by finishing my homework from my Geometric Series assignment, then I'll be learning how to use Python to modify text files.


 

This afternoon, I'm learning from this DigitalOcean article that covers the basics of opening, reading, and writing files.


I started by creating a new Python file, then creating a text file in the same folder. I populated the text files with the days of the week, then told the program to open the file, but didn't get any output. After a bit of Googling, I found that someone had run into the same problem; Levon on Stack Overflow had an answer: merely opening the file doesn't show any output; I have to print the information that I tell the program to read if I want to be able to see it. I had to play around with the code a bit to make it work for me, but eventually, I was able to get the program to show the output on the screen. I was ready to move on to the next section, writing to a file, and realized that this tutorial didn't have the info I was looking for: I want to figure out how to delete information from an existing file. I went back to StackOverflow and found a really helpful thread that talked about exactly that.


I learned that Python doesn't actually support deleting lines; instead, Python requires us to read a file, create a temporary file, move the information from the original file except for the undesired information to the temporary file, then overwrite the original file with the temporary file, finally deleting the temporary file. In the example that I found, the code was being used to print off 10 lines of code; I made a couple of adjustments so that it only printed off one line at a time - and it worked!



The next step was to find a way to integrate it with my Randomizer so that I wouldn't need to manually delete items from my Albums.txt file any more.


It was a lot easier than I expected. I just popped it in to the code, set up the printout as a variable instead, and tested it. It worked perfectly. The albums were automatically deleted from the listing each time I ran the program again. I did notice that since I was rewriting the lines with a newline inserted between each data set, I was ending up with a blank line at the end of the file. I at first thought this was a problem; after a bit of Googling, I found out that this is actually expected and will not be read from. Winning!


The final steps I took were to turn off the autorun on my Randomizer so that restarting my computer won't cause me to accidentally lose albums from my lines, then I updated my Gist code.

bottom of page