Python homework part.2

Python homework part.2



This time we only had four exercises dealing with the reading, writing in, overwriting and searching documents with python.

I managed to complete all of these quite quickly and only found a challenge in the exercise 3/4 which you can see below. I'll ad some screenshots to these too from here on.


Read a document called faktat.txt and print what it said.



document = open("faktat.txt","r")
contents = document.readlines()
print("Tiedostosta luettiin teksti: ")

for i in (contents):




The second exercise had us write a short program that asks the user to input what the written file is going to be called and then asks for what to write in to the said file.


tiedosto = input("What will the file be named: ")
text = input("What to write in the file: ")
file = open(tiedosto,"w")

print("Created file ",tiedosto,"and wrote: ", text)


This one was the trickier one I spoke about previously. The goal of this exercise was to read through some randomly generated character sequences and check if they consist only of numbers and letters. No special characters were allowed. The trouble I had in this one was with me not realizing that while using the isalnum() function with the readlines() function the space/newline that readlines() adds at the end of each read line of text gets read also by the isalnum() function, so it returned all as false. To fix this issue I removed the space readlines() adds as you'll see below.


file = open("merkkijonoja.txt", "r")
content = file.readlines()

for i in content:
    i = i[:-1]
    if i.isalnum()==False:
        print(i, "sisältää virheellisiä merkkejä.")
        print(i, "kelpaa salasanaksi.")


The line i = i[-1] takes out the space after the printed line.


I altered the output in to English from the original Finnish for this screenshot.


The last one of this bunch was a read, write, delete notebook that works in a loop. Based on user selection between 1 and 4 the program performs different actions to the notebook.


Again switched some of the programs text from original Finnish to English for this screenshot.


start = True

while start:
    print("(1) Read notebook\n(2) Add to notebook\n(3) Empty notebook\n(4) Quit")
    userselection = int(input("What do you wish to do? : "))
    if userselection == 1:
        file = open("muistio.txt","r")
        content = file.readlines()
        for i in content:
    elif userselection == 2:
        file = open("muistio.txt","a")
        addText = input("Add note: ")
    elif userselection == 3:
        file = open("muistio.txt","w")
        print("Notebook emptied.")

    elif userselection == 4:
        start = False

Next up will be what our course calls "sub-functions".


  • Picture: