Files are great because we can write data to them before we close a computer program. This means that the data is not lost.
Here is an example of a text file that stores permanent data.
Let's try and open it and read the contents:
import time
f = open("CarSales.txt", "r")
#store the first line in a variable
line = f.readline()
#start a loop to read every line in the file
while line:
time.sleep(0.5)
#strip any invisible newline characters /n from the end of the line of text (string)
line = line.strip()
print(line)
#get the next line
line = f.readline()
#don't forget to close the file.
f.close()
This textfile is interesting because each value is seperated by a comma.
Python can handle this very well by calling the split() function. This will put every string between each comma into an array!
So, now our code can look like this:
f = open("CarSales.txt", "r")
line = f.readline()
while line:
time.sleep(0.5)
line = line.strip()
#push the contents of each item seperated by a comma into an array - we now have an array of Strings!
lineArray = line.split(',')
print(lineArray)
#get the next line
line = f.readline()
#don't forget to close the file.
f.close()
So now as we loop through each line of the file, we can turn it into an array and then we can do some processing:
f = open("CarSales.txt", "r")
carCoice = input("Which type car do you want to count (eg MicroZed): ")
count = 0
line = f.readline()
while line:
line = line.strip()
#push the contents of the line into an array
lineArray = line.split()
#the second element of the array is the type of car
if lineArray[1] == carChoice:
count+=1
#get the next line
line = f.readline()
print(f"There are {count} {carChoice} in the data file")
#don't forget to close the file.
f.close()