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

Show parent comments

1

u/[deleted] Dec 08 '21

Firstly, the wiki I mentioned, and my comments in general, were related to the r/learnpython subreddit - forgot where I was.

You can read the first row, as a header, using next (whether simple text file or csv file).

import csv

with open('MOCK_DATA-3.txt') as data_source:
    reader = csv.reader(data_source)
    header = next(reader)  # this will be a list of header names
    rows = []
    for row in reader:
        # could make changes to row before appending below
        rows.append(row)  # builds up internal copy of data

Now your rows list contains nested lists. You can sort on any entry using the key option in sorted. Keep in mind how different cases impact sorting.

You could have using slicing instead to sort just rows[1:], ignoring the header row. Look up list slicing.

1

u/KeganBergi Dec 13 '21

This is the code that I have so far, it has quite a few red line errors I'm using due to missing header files of some sorts, the last thing I need is the line for the...

for record in data[1:]:

I'm having a hard time writing the nested loop.

This is the code that I have so far, it has quite a few redline errors I'm using due to missing header files of some sort, the last thing I need is the line for the inputFile:

for line in inputFile.readlines():

returnList.append(line.strip().split('\t'))

return returnList

execpt FileNotFoundError:

print(f"File): {filename} doesn't exist")

exit()

def orderHeader(headerToOrder):

headerToReturn = headerToOrder.copy()

headerToReturn.sort()

return headerToReturn

def buildNewHeader(oldList, newList):

def createData(header, data):

newColumnList = []

oldColumnList = data[0]

for field in header:

newColumnList.append(oldColumnList.index(field))

newData = []

newData.append(buildNewHeader(oldColumnList, newColumnList))

for record in data[1:]:

return newData

def writeFile(listToWrite, filename):

dataList = readFile(assingmentFileName)

newHeader = orderHeader(dataList[0])

sortedDataList = createData(newHeader, dataList)

writeFile(sortedDataList, outputFilename)

1

u/[deleted] Dec 13 '21

Any chance you could edit that to show the indents correctly? Instructions are in the wiki, link in sidebar.

1

u/KeganBergi Dec 14 '21

I've changed to the different editor in reddit and everytime I paste my code it still has a hard time formatting ALL of the code some gets turned into the off gray box but the rest gets jumbled