r/pythonhelp • • Dec 08 '21

PYTHON ASSIGNMENT PLS SOMEONE LOL

Read in the included data file and write it to a file named sorted_data.txt with the same data, but order the columns in ascending alphabetical order.

https://www.dropbox.com/s/snhowdtcne6zuuf/MOCK_DATA-3.txt?dl=0

That is the link to the data file that is supposed to be initially read in.

1 Upvotes

16 comments sorted by

View all comments

3

u/[deleted] Dec 08 '21

Not signing into a Dropbox account account to open some random file from a stranger on the Internet.

Include a sample of the data showing the format in your post and also what you've done so far.

The standard way to read a text file would be,

with open('MOCK_DATA-3.txt') as data_source:
    for line in data_source:
        # do something with the string referenced by line

It is possible to read all of the lines in a file in one go, but it is assumed you will want to process each line to extract the data into a required format.

If the file is formatted in a standard way such as CSV, comma separated values (other separators than comma can be used) then the CSV module will help.

import csv

with open('MOCK_DATA-3.txt') as data_source:
    reader = csv.reader(data_source)
    for row in reader:
        # do something with the **list** that is referenced by row

This looks similar but the csv module reads data into a list rather than one string, saving you some work.

Good guide: https://realpython.com/python-csv/

1

u/KeganBergi Dec 08 '21

Yeah I can understand your worries, Its a downloaded datafile from Mockaroo, contains random shit, what needs to be done is taking the header of the data then creating a new txt file having the data rows in ascending order all alphabetically.

1

u/[deleted] Dec 08 '21

Still need to see the format of the lines.

If the lines are just single text lines, then read them all into a list and use the sort method (or sorted function) on the list, then write the lines out again.

If the lines are columns of data, so each line is a record, use the CSV method and store all the lists (records) in one big list and sort that list on a specific column. This uses the key option of sorted.

Good article: https://realpython.com/python-sort/