83.5k views
3 votes
Which of the following answers' code statement prints the last field in each row of the csv file?

User Emerito
by
8.3k points

1 Answer

6 votes

The correct statement is: c. with open('my_file.csv', 'r') as f: csv_data = csv.reader(f) for r in csv_data: print(r[-1])

Option c reads a CSV file named 'my_file.csv', uses the 'csv.reader()' function to parse the file, and iterates through each row in the CSV data. For each row (represented by 'r'), it prints the last field of that row using 'print(r[-1])'.

This approach correctly accesses the last element in each row, as indexing '-1' refers to the last element in Python. The other options contain syntax errors or incorrect methods for accessing CSV data. Therefore, option c provides a functional and accurate solution for printing the last field in each row of the CSV file.

The complete question is:

Which of the following statements prints the last field in each row of the csv file? a. with open('my_file.csv', 'r') as f: csv_data = csv. reader(1-11) print(csv_data) b. with open('my_file.csv', '') as f: csv_data - esv. reader(f) print(csv_data (-11) c. with open('my_file.csv', 'r') as f csv_data = csv. reader (1) for r in csv_data: print(0:-11) d. with open('myfile.csv.) as f: csv_data = csv. reader) for r in csv_data: printirl-11)

User Nshy
by
7.6k points