The WSQ16 is about doing a program that reads a file abaut cars and it’s specifications. The file is read such as the first 14 characters are the model o f the car, the character from 53 to 54, the miles per gallon in city, and so on.
So it asks you to give the user the average gas mileage in city (City MPG), average gas mileage on highway (Highway MPG), and the average midrange price of the vehicles in the set.
To accomplish that, I searched for a way to import text files to python and how to read it.
I learned that you can open the file, the easy way, with the command open(“nameofthefile.extension”)…. yeah, that simple.
Then, the hard part goes on, read the file
Let’s say you code this
file = openfile(“filename.ext”)
The token file has the file in it.
The file can be read line by line with the command file.readline()
The file can be read entirely and set as a list with the command file.read()
Through websurfing I learned another way; you can read text lines with for loops; you just have to tell the computer for each line inside this variable do:
And the result of hte coding is:
for line in file
After discoveringt that, the coding was so easier.
It all abaout substrings; I already know what spaces are what thing, so I just substring with line[start:end] so its easy then, just have to assing a variable like carmodel or cmpg and print it continiously inside the loop.
The last problem was that I didn’t need the even lines, so with an if and the condition a counter is even, I skipped every even line.
Here is the result:
As always
WSQ16: Opening files and reading them by charliegdrummer is licensed under a Creative Commons Attribution 4.0 International License.