We will now use this file as input in a program that will do some data processing. In the program, we will examine each line of the file and print it with some additional text. Because readlines()
returns a list of lines of text, we can use the for loop to iterate through each line of the file.
To make the code a little simpler, and to allow for more efficient processing, Python provides a built-in way to iterate through the contents of a file one line at a time, without first reading them all into a list. Some students find this confusing initially, so we don’t recommend doing it this way, until you get a little more comfortable with Python. But this idiom is preferred by Python programmers, so you should be prepared to read it. And when you start dealing with big files, you may notice the efficiency gains of using it.
Data: olympics.txt
Name,Sex,Age,Team,Event,Medal
A Dijiang,M,24,China,Basketball,NA
A Lamusi,M,23,China,Judo,NA
Gunnar Nielsen Aaby,M,24,Denmark,Football,NA
Edgar Lindenau Aabye,M,34,Denmark/Sweden,Tug-Of-War,Gold
Christine Jacoba Aaftink,F,21,Netherlands,Speed Skating,NA
Christine Jacoba Aaftink,F,25,Netherlands,Speed Skating,NA
Christine Jacoba Aaftink,F,25,Netherlands,Speed Skating,NA
Christine Jacoba Aaftink,F,27,Netherlands,Speed Skating,NA
Per Knut Aaland,M,31,United States,Cross Country Skiing,NA
Per Knut Aaland,M,33,United States,Cross Country Skiing,NA
John Aalberg,M,31,United States,Cross Country Skiing,NA
John Aalberg,M,33,United States,Cross Country Skiing,NA
"Cornelia ""Cor"" Aalten (-Strannood)",F,18,Netherlands,Athletics,NA
"Cornelia ""Cor"" Aalten (-Strannood)",F,18,Netherlands,Athletics,NA
Antti Sami Aalto,M,26,Finland,Ice Hockey,NA
"Einar Ferdinand ""Einari"" Aalto",M,26,Finland,Swimming,NA
Jorma Ilmari Aalto,M,22,Finland,Cross Country Skiing,NA
Jyri Tapani Aalto,M,31,Finland,Badminton,NA
Minna Maarit Aalto,F,30,Finland,Sailing,NA
Minna Maarit Aalto,F,34,Finland,Sailing,NA
Pirjo Hannele Aalto (Mattila-),F,32,Finland,Biathlon,NA
Timo Antero Aaltonen,M,31,Finland,Athletics,NA
Win Valdemar Aaltonen,M,54,Finland,Art Competitions,NA