The Red Penguin

File handling


Monday 9 November 2020

This code opens a file stored in the same directory as your python file, reads it and then closes the file:
f = open("textfile.txt", "r")
data = f.read()
f.close()
# opens the file, reads the data into a string called data and then closes it
We can then do things with the data:
words = data.split(" ")
# creates a list with all of the words in it

print(words)
# outputs ['The', 'quick', 'brown', 'fox', 'jumped', 'over', 'the', 'lazy', 'dog']

print(len(words))
# outputs 9
Let's add some code to see if we can count the instances in the "words" list.
counter = {}
# create an object called counter

for i in words:
if i in counter:
counter[i] += 1
else:
counter[i] = 1

print(counter)
# outputs {'The': 1, 'quick': 1, 'brown': 1, 'fox': 1, 'jumped': 1, 'over': 1, 'the': 1, 'lazy': 1, 'dog': 1}
I think what is happening here is that we are creating a dictionary, and then looking at each member of the words list and if it's in the list, adding one to the dictionary key.
More posts in python