Menu

[Solved]-Python Reading Chapter Programming Assignment Re Read Toolbos 71 Working Csv Files Section Q37176419

7.2 Text Input and Output 399 Working with CSV Files You have seen how to read and write text files and to but what if you ne

r 400 Chapter 7 Files and Exceptions The fo from he ile nd During each iteration of the loop, the data for one complete row i

7.3 Command Line Arguments 401 The following program accomplishes this task. ch07/toolbox.1/filter.py 2 This program reads da

PYTHON ONLY

After reading the chapter and doing the programming assignment,re-read the ToolBos 7.1 Working with CSV Files section (p.399-401). Type in the commands as instructed. Play with it, seewhat happens.

Then, run the file program on page 401 using this as the inputmovies.csv file. You may need to add the full path to the two csvfiles used in the program (remember to include two backslashes foreach single backslash). When finished processing, the programshould produce an output file.

7.2 Text Input and Output 399 Working with CSV Files You have seen how to read and write text files and to but what if you need to process data stored in a spreadsheet? For example, suppose you nee to print a list of all the movies released in the 1990s from a spreadsheet filled with movie data, s works s data stored in various formats, s a regu- such as the one shown below. 1951 wnam Wyier Mamiet Bitter Moon Round Midnight 1996 Kenneth Branagh 999 Sam Mendes 992 Roman Polanski 4 American Beauty 2004 CiM Eastwood on 8 Kiss of the Spider Woman 1905 Hector Babenco 2000 Steven Soderbergh Most spreadsheet applications store their data in proprictary file formats that cannot accessed directly by other programs. Fortunately, most can save a copy ble format known as CsV (Comma-Separated Values). A CSV file is simply a text file in whi each row of the by commas. be of the data in a porta- er t, the spreadsheet is stored as a line of text. The data values in each row are separated For example, the CSV file created from the spreadsheet shown above contains: “Detective Story”, “1951,”willian Wyler” “Airport 1975. “1974”, “Jack Snight’ “Hanlet”,”1996″,”Kenneth Branagh American Beauty”, “1999”, “San Mendes Bitter Moon”, “1992, “Ronan Polanski “Million Do11ar Baby, “2004, “Clint Eastwood” Round Nidnight, “1986”, “Bertrand Tavernier kiss of the Spider Wonan”. “1985”,”Héctor Babenco Twin Falls Idaho”, “1999” “Michael Polish” “Traffic”, “2000”, “Steven Soderbergh” d Code find in as sym- is 65 ed their 255 for ece, the named CSV files are so common that the Python standard library provides tools for working with them. In this section, we explore the csv module and how to work with CSV files in Python. omput r, there s called A is still Reading a CSV File To read the contents of a CSV file, you must first open the file as a regular text file, 8 when not yet system infile 0pen(“novies1.csv..) then create a CSV reader using the reader function: . That’s he same ,or spe- from csv import reader csvReader reader (infile) You can use a for loop to iterate through the data in the CSV reader object. For example for row in csvReader : print (row) onsider e in the 8 or Á it reads and prints each row of data from the CSV file in this format: I’Detective Story’, ‘1951’, ‘william Wyler’] L’Airport 1975, ‘ . 1974”,リack Smight] can’t coding t’Kiss of the Spider Woman’, ‘1985, ‘Héctor Babenco’] [‘Twin Falls Idaho’, 1999, ‘Michael Polish’ [‘Traffic’, ‘2000, ‘Steven Soderbergh’1 r 400 Chapter 7 Files and Exceptions The fo from he ile nd During each iteration of the loop, the data for one complete row is read variable row as a list of strings. For each row, the list can cho7 y other list. Here, we complete the original task of printing the tlesofall movies released in the 1990s: from esv irport reader Open the text file and create a CSV reader. infile open(“roviesi.csv csvReader-reader(infile) ” Read the rows of data. for row in csvReader: 10 year int (row[1]) f year >-1990 and year “1999 printCrow[o]) Because the data is read and stored as a list of strings, you have to convert numerical da appropriate numerical format before using those values. In our loop, we convert the v to an integer before testing it. to year vahue You can skip a row by using Python’s next function with the CSV reader. For example e row(s) containing that information: next(csvReader) , iz spreadsheet contains descriptive information, such as a title or column headin you can Creating a CSV File To create a CSV file from a Python program, first create a new text file using the opef Then create a CSV writer using the writer function from the csv module: To add a row of data to the CSV file, use the writer” method. You pass a list of the row’s dní outfile open(“newdata.csv”, “w”) from csv irport writer cswiriter – writer(outfile) to this method. For example, to add a row of column headers, you would pass alist of string one for each column in the spreadsheet. You can add numbers or a mixture of text and numbers: To skip a row in the CSV file, you pass an empty list to the writerow method. After writing the data to the CSV file, you must remember to close the file: csvwriter.writerow([“Nane”, “Id”, “Class”, “Average ]) 7.3 Com csvwriter.writerow([“John Smith, 1607, “Senior”, 3.28]) csviri ter, wri terow[]) outfile.closeO Processing a CSV File Here is an example that illustrates both reading from and writing to a CSV file. Suppose you are given the task of creating a new CSV file that contains a limited amount of information from a much larger collection of movie data. Specifically, the new file should contain only the title, year of release, and list of the actors for those movies released in the 1990s. If the input CSV file contains the 5 columns “Nane”, “Year”, “Directors”,”Producers”. “Actors then the new file should contain only the first two and the last column of data and only those rows that contain movies from the 1990s, with the appropriate column headings 7.3 Command Line Arguments 401 The following program accomplishes this task. ch07/toolbox.1/filter.py 2 This program reads data from a csv file that contains movie information, 3 filters out unwanted data, and produces a new csv file. # 6 from csv inport reader, writer Open the two csv files. 9 infile openC novies.csv”) 10 csvReader reader (infile) 12 outfile openC” filtered.csv”, “w 13 csvWriter writer(outfile) 14 15 # Add the list of column headers to the csv file. 16 headers= [“Name.” Year”, “”Actors”] 17 csvwriter.writerow(headers) 18 19 # skip the row, of column headers in the reader 20 next(csvReader) 21 22 # Filter the rows of data. 23 for row in csvReader 24 year int (row[1]) 25 if year >- 1990 and year – 1999: 26 newRow [row[O], row[1], rowt4]) 27 csvwriter.writerow(newRow) 28 29 infile.closeO 30 outfile.closeO 7.3 Command Line Arguments Depending on the operating system and Python development environment used, there are different methods of starting a program-for example, by selecting “Run” in the development environment, by clicking on an icon, or by typing the name of the program at the prompt in a terminal window. The latter method is called “invok ing the program from the command line”. When you use this method, you must of course type the name of the program, but you can also type in additional information that the program can use. These additional strings are called command line argu- ments. For example, if you start a program with the command line python program.py -v input.dat then the program receives two command line arguments: the strings “-v and “input.dat”. It is entirely up to the program what to do with these strings. It is cus- Should you support command line arguments for your programs, or should you prompt users, perhaps with a graphical user interface? For a casual and infrequent an interactive user interface is much better. The user interface guides the user tomary to interpret strings starting with a hyphen (-) as program options. Show transcribed image text 7.2 Text Input and Output 399 Working with CSV Files You have seen how to read and write text files and to but what if you need to process data stored in a spreadsheet? For example, suppose you nee to print a list of all the movies released in the 1990s from a spreadsheet filled with movie data, s works s data stored in various formats, s a regu- such as the one shown below. 1951 wnam Wyier Mamiet Bitter Moon Round Midnight 1996 Kenneth Branagh 999 Sam Mendes 992 Roman Polanski 4 American Beauty 2004 CiM Eastwood on 8 Kiss of the Spider Woman 1905 Hector Babenco 2000 Steven Soderbergh Most spreadsheet applications store their data in proprictary file formats that cannot accessed directly by other programs. Fortunately, most can save a copy ble format known as CsV (Comma-Separated Values). A CSV file is simply a text file in whi each row of the by commas. be of the data in a porta- er t, the spreadsheet is stored as a line of text. The data values in each row are separated For example, the CSV file created from the spreadsheet shown above contains: “Detective Story”, “1951,”willian Wyler” “Airport 1975. “1974”, “Jack Snight’ “Hanlet”,”1996″,”Kenneth Branagh American Beauty”, “1999”, “San Mendes Bitter Moon”, “1992, “Ronan Polanski “Million Do11ar Baby, “2004, “Clint Eastwood” Round Nidnight, “1986”, “Bertrand Tavernier kiss of the Spider Wonan”. “1985”,”Héctor Babenco Twin Falls Idaho”, “1999” “Michael Polish” “Traffic”, “2000”, “Steven Soderbergh” d Code find in as sym- is 65 ed their 255 for ece, the named CSV files are so common that the Python standard library provides tools for working with them. In this section, we explore the csv module and how to work with CSV files in Python. omput r, there s called A is still Reading a CSV File To read the contents of a CSV file, you must first open the file as a regular text file, 8 when not yet system infile 0pen(“novies1.csv..) then create a CSV reader using the reader function: . That’s he same ,or spe- from csv import reader csvReader reader (infile) You can use a for loop to iterate through the data in the CSV reader object. For example for row in csvReader : print (row) onsider e in the 8 or Á it reads and prints each row of data from the CSV file in this format: I’Detective Story’, ‘1951’, ‘william Wyler’] L’Airport 1975, ‘ . 1974”,リack Smight] can’t coding t’Kiss of the Spider Woman’, ‘1985, ‘Héctor Babenco’] [‘Twin Falls Idaho’, 1999, ‘Michael Polish’ [‘Traffic’, ‘2000, ‘Steven Soderbergh’1
r 400 Chapter 7 Files and Exceptions The fo from he ile nd During each iteration of the loop, the data for one complete row is read variable row as a list of strings. For each row, the list can cho7 y other list. Here, we complete the original task of printing the tlesofall movies released in the 1990s: from esv irport reader Open the text file and create a CSV reader. infile open(“roviesi.csv csvReader-reader(infile) ” Read the rows of data. for row in csvReader: 10 year int (row[1]) f year >-1990 and year “1999 printCrow[o]) Because the data is read and stored as a list of strings, you have to convert numerical da appropriate numerical format before using those values. In our loop, we convert the v to an integer before testing it. to year vahue You can skip a row by using Python’s next function with the CSV reader. For example e row(s) containing that information: next(csvReader) , iz spreadsheet contains descriptive information, such as a title or column headin you can Creating a CSV File To create a CSV file from a Python program, first create a new text file using the opef Then create a CSV writer using the writer function from the csv module: To add a row of data to the CSV file, use the writer” method. You pass a list of the row’s dní outfile open(“newdata.csv”, “w”) from csv irport writer cswiriter – writer(outfile) to this method. For example, to add a row of column headers, you would pass alist of string one for each column in the spreadsheet. You can add numbers or a mixture of text and numbers: To skip a row in the CSV file, you pass an empty list to the writerow method. After writing the data to the CSV file, you must remember to close the file: csvwriter.writerow([“Nane”, “Id”, “Class”, “Average ]) 7.3 Com csvwriter.writerow([“John Smith, 1607, “Senior”, 3.28]) csviri ter, wri terow[]) outfile.closeO Processing a CSV File Here is an example that illustrates both reading from and writing to a CSV file. Suppose you are given the task of creating a new CSV file that contains a limited amount of information from a much larger collection of movie data. Specifically, the new file should contain only the title, year of release, and list of the actors for those movies released in the 1990s. If the input CSV file contains the 5 columns “Nane”, “Year”, “Directors”,”Producers”. “Actors then the new file should contain only the first two and the last column of data and only those rows that contain movies from the 1990s, with the appropriate column headings
7.3 Command Line Arguments 401 The following program accomplishes this task. ch07/toolbox.1/filter.py 2 This program reads data from a csv file that contains movie information, 3 filters out unwanted data, and produces a new csv file. # 6 from csv inport reader, writer Open the two csv files. 9 infile openC novies.csv”) 10 csvReader reader (infile) 12 outfile openC” filtered.csv”, “w 13 csvWriter writer(outfile) 14 15 # Add the list of column headers to the csv file. 16 headers= [“Name.” Year”, “”Actors”] 17 csvwriter.writerow(headers) 18 19 # skip the row, of column headers in the reader 20 next(csvReader) 21 22 # Filter the rows of data. 23 for row in csvReader 24 year int (row[1]) 25 if year >- 1990 and year – 1999: 26 newRow [row[O], row[1], rowt4]) 27 csvwriter.writerow(newRow) 28 29 infile.closeO 30 outfile.closeO 7.3 Command Line Arguments Depending on the operating system and Python development environment used, there are different methods of starting a program-for example, by selecting “Run” in the development environment, by clicking on an icon, or by typing the name of the program at the prompt in a terminal window. The latter method is called “invok ing the program from the command line”. When you use this method, you must of course type the name of the program, but you can also type in additional information that the program can use. These additional strings are called command line argu- ments. For example, if you start a program with the command line python program.py -v input.dat then the program receives two command line arguments: the strings “-v and “input.dat”. It is entirely up to the program what to do with these strings. It is cus- Should you support command line arguments for your programs, or should you prompt users, perhaps with a graphical user interface? For a casual and infrequent an interactive user interface is much better. The user interface guides the user tomary to interpret strings starting with a hyphen (-) as program options.

Expert Answer


Answer to PYTHON ONLY After reading the chapter and doing the programming assignment, re-read the ToolBos 7.1 Working with CSV Fi… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *