Write a function sort_records(csv_filename, new_filename) that sorts the records of a CSV file and writes the results as a new CSV file. The first column of the CSV file will be the city name. The rest of the columns will be months of the year. The first row of the CSV file will take the form of the column headings, with all columns other than the first being months of the year. Here is an example file fragment:max_temp.csvcity/month,Jan,Feb,Mar,AprMelbourne,41.2,35.5,37.4,29.3Brisbane,31.3,40.2,37.9,29Darwin,34,34,33.2,34.5Note that your code will be tested over different CSV files, with different ranges of months in them. Irrespective of the exact months contained in the file, you may assume that the city name will always be in the first column, and the months in the remaining columns.You must sort the data in alphabetical order according to the city name (stored in the first column). Your program should write the sorted records to a new file with the name given by the argument new_filename.Here is an example of how sort_records() should work. 'program.py' is the program and below is its terminal output.sort_records('max_temp.csv', 'sorted.csv')result = open('sorted.csv')print(result.read())result.close()city/month,Jan,Feb,Mar,AprBrisbane,31.3,40.2,37.9,29Darwin,34,34,33.2,34.5Melbourne,41.2,35.5,37.4,29.3Note that the row for Melbourne has been sorted below the rows for Brisbane and Darwin because Melbourne comes after Brisbane and Darwin, based on alphabetical ordering.
Question
Write a function sort_records(csv_filename, new_filename) that sorts the records of a CSV file and writes the results as a new CSV file. The first column of the CSV file will be the city name. The rest of the columns will be months of the year. The first row of the CSV file will take the form of the column headings, with all columns other than the first being months of the year. Here is an example file fragment:max_temp.csvcity/month,Jan,Feb,Mar,AprMelbourne,41.2,35.5,37.4,29.3Brisbane,31.3,40.2,37.9,29Darwin,34,34,33.2,34.5Note that your code will be tested over different CSV files, with different ranges of months in them. Irrespective of the exact months contained in the file, you may assume that the city name will always be in the first column, and the months in the remaining columns.You must sort the data in alphabetical order according to the city name (stored in the first column). Your program should write the sorted records to a new file with the name given by the argument new_filename.Here is an example of how sort_records() should work. 'program.py' is the program and below is its terminal output.sort_records('max_temp.csv', 'sorted.csv')result = open('sorted.csv')print(result.read())result.close()city/month,Jan,Feb,Mar,AprBrisbane,31.3,40.2,37.9,29Darwin,34,34,33.2,34.5Melbourne,41.2,35.5,37.4,29.3Note that the row for Melbourne has been sorted below the rows for Brisbane and Darwin because Melbourne comes after Brisbane and Darwin, based on alphabetical ordering.
Solution
Sure, here is a Python function that does what you described:
import csv
def sort_records(csv_filename, new_filename):
with open(csv_filename, 'r') as csv_file:
reader = csv.reader(csv_file)
data = list(reader)
header = data[0]
records = data[1:]
records.sort()
sorted_data = [header] + records
with open(new_filename, 'w', newline='') as new_file:
writer = csv.writer(new_file)
writer.writerows(sorted_data)
This function works as follows:
-
It opens the input CSV file and reads its contents using the
csv.readerfunction. It converts the reader object to a list, which gives us a list of lists where each inner list represents a row in the CSV file. -
It separates the header row (the first row) from the rest of the data. It then sorts the data (excluding the header) in alphabetical order. The
sortmethod of a list in Python sorts the list in place, and when used on a list of lists, it sorts by the first element of each inner list, which in this case is the city name. -
It combines the header and the sorted data into a new list.
-
It opens the output CSV file and writes the sorted data to it using the
csv.writerfunction. Thewriterowsmethod of acsv.writerobject writes multiple rows to the CSV file.
Please note that this function assumes that the input CSV file exists and is in the correct format, and that the program has permission to create and write to the output CSV file. If these conditions are not met, the function may raise an exception.
Similar Questions
Write a function max_city_temp(csv_filename, city) which analyses temperatures recorded in a CSV file, and returns the maximum temperature recorded for the named city.Once again, the first column of the CSV file will be the city name, and the rest of the columns will be months of the year. The first row of the CSV file will provide the column headings. Here is an example file fragment:max_temp_small.csvcity/month,Jan,Feb,Mar,AprMelbourne,41.2,35.5,37.4,29.3Brisbane,31.3,40.2,37.9,29Darwin,34,34,33.2,34.5Here is an example of how max_city_temp() should work:>>> max_city_temp('max_temp_small.csv', 'Brisbane')40.2
write a function read_data(filename) that retrieves the data from the given file filename (the file is in CSV format) by returning every entry INCLUDING the headings (the headings always exist in given files, this will be used later for finding indices of columns) as a single list. Each entry should be a list containing data separated by a comma, and any new line characters at the end of each row should be stripped off. It's important to note that no imports should be used for this task.You may assume there are no errors in the given and tested files.For example:Test Input Resultdata = read_data('CreditCard_2024.csv')print(data[0])CreditCard_2024.csvTransactionID,TimeStamp,CardNumber,Transaction_type,Type_of_card,Entry_mode,Amount,Actual,Origin,Class
SortWrite a Python program that sorts all lines alphabetically within a text file.The program will be given 2 command line arguments: the first specifies the path to the file to sort, and the second specifies the column number to use as the key for sorting the file.Columns are numbered starting from 1. You can assume columns in the file are separated by a space " ", and that the column number provided is a valid column in the file.If the value in one column is a duplicate, the program sorts the lines with the duplicate value in alphabetical order based on the contents of their entire lines from start to finish.You should write your solution in sort.py.Example output$ cat students.txtMicheline Lalevee [email protected] USYDRobyn Maes [email protected] USYDVenus Kinsley [email protected] USYDDevonne Berrygun [email protected] UNSWLuci Broad [email protected] UTSMorissa Bolino [email protected] MacquarieDanika Heatley [email protected] WSURichmond Goodnow [email protected] USYD$ python3 sort.py students.txt 2Devonne Berrygun [email protected] UNSWMorissa Bolino [email protected] MacquarieLuci Broad [email protected] UTSRichmond Goodnow [email protected] USYDDanika Heatley [email protected] WSUVenus Kinsley [email protected] USYDMicheline Lalevee [email protected] USYDRobyn Maes [email protected] USYDError handlingIf the user does not provide exactly 2 command line arguments, print Error: must provide exactly 2 arguments to stderr, and exit the programIf the file does not exist, print Error: '<filename>' cannot be found to stderr, and exit the programYou may assume that all files provided to the program are valid text files, and the user has read permissions on all input files.Note: Your coding style will be examined, so take this into consideration for your solution.Be careful when sorting a column with numbers – sorting numbers alphabetically is different to sorting numbers numerically!You may only use the sys module – no other imports are allowed for this task.
Write a Python program that sorts all lines alphabetically within a text file.The program will be given 2 command line arguments: the first specifies the path to the file to sort, and the second specifies the column number to use as the key for sorting the file.Columns are numbered starting from 1. You can assume columns in the file are separated by a space " ", and that the column number provided is a valid column in the file.If the value in one column is a duplicate, the program sorts the lines with the duplicate value in alphabetical order based on the contents of their entire lines from start to finish.You should write your solution in sort.py.
Write down the steps to sort the Name column in ascending order
Upgrade your grade with Knowee
Get personalized homework help. Review tough concepts in more detail, or go deeper into your topic by exploring other relevant questions.