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

Also another thing, I've actually never posted anything to reddit, this was truly my last resort, tutoring didn't even help, it's honestly sickening me knowing that I can't do a simple index() and sort() with two nested for loops

1

u/[deleted] Dec 08 '21 edited Dec 08 '21

There's a lot of people starting out on this subreddit and getting great help. Some people take to programming very quickly but others find it very difficult at first and it takes a lot of effort to get it.

I help a lot of kids learn to programme through the Code Club organisation, working in local schools, and also sometimes teach adults at local community college.

For most of those who find it difficult, I find the problem is usually that they assume the computer is far more intelligent than it actually is. They find it difficult to dumb things down sufficiently for a very stupid (compared to a human) machine. This is partly because it is hard as humans to see all the leaps we make when carrying out tasks.

I give some people an exercise to sort a small set of cards, say 10 number cards, that have been shuffled, into the correct order. Most people can do this very quickly and easily. However, when I say to write down the instructions for someone with significant learning difficulties, assuming they have a very short memory, can only hold one card in their hand at a time, people find it a lot more challenging than they expected. I get them to put a load of bits of paper down on the table, with labels on them A .. J. And an extra bit of paper off to the side as a holding area. It takes a while and is very irritating for some when I play the computer and do dumb stuff because I've not got an instruction to do anything else.

It is definitely worth looking at the learning guidance and materials in the wiki for this subreddit. There's some great content.

The only way to learn though is practice! Practice! Practice! With lots of failure and experimentation. I recommend people make use of the Python Interactive Shell, the one with the >>> prompt in IDLE, as you get instant feedback when trying things out, and don't need to use long variable names, real data - just quickly check how to do something simple.

Did the example code I shared make any sense?

EDIT: The wiki is for the /r/learnpython subreddit - forgot where I was.

1

u/KeganBergi Dec 08 '21

The example is perfect, I know how to read in the file of mock data with... file open("MOCK-DATA3.txt") along with sorting the data, but obviously, it does work but it sorts literally everything in alphabetical order, I just need to index the first row being the header, with the... data[0:] command which then pinpoints where each of the first words for the header, the assignment states I need a "was is" list. In that sense I get that I need to keep the old data and copy it to a new list to work from.

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 08 '21

You describe how to do this perfectly, I'm going to try and implement this the best I can.

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

1

u/KeganBergi Dec 14 '21

from os import path

dataFileName = "pythonData.txt" outputFilename = "sorted_data.txt" HomeFolder = path.expanduser('~')

fullFileName = path.join(HomeFolder, "downloads", dataFileName)

userProfiles = {}

try: with open(dataFileName, 'r') as inputFile, open(outputFilename, 'w') as outputFile: NewList = [] fileHeader = inputFile.readline() for inputLine in inputFile.readlines(): cleanLine = inputLine.strip() id, first_name, last_name, email, gender, ip_address, favorite_color, ssn, buzzword, animal_name = cleanLine.split('\t') userProfiles = [animal_name, buzzword, email, favorite_color, first_name, gender, id, ip_address, last_name, ssn] print(userProfiles) outputFile.write('\t'.join(userProfiles) + '\n') pass except FileNotFoundError: print(f"ERROR: File {fullFileName} doesn't exist! ):")

1

u/KeganBergi Dec 14 '21

as you can see, it still likes to become a jumbled mess.

1

u/[deleted] Dec 16 '21 edited Dec 16 '21

You need to:

  • switch Reddit posting to markdown mode from fancy pants mode

  • create/edit a post/comment, write intro text followed by a blank line

  • switch to your Python code editor

  • select ALL the code in your editor and press tab to insert an additional 4 spaces in front of every line (assuming you've configured your editor to use spaces rather than tabs and use 4 spaces by default when tab key is used)

  • copy all the code in your editor and paste it into Reddit post/comment

  • add a blank line after the code block

  • don't forget to undo the additional indent in your code editor

Alternatively, use a paste service like pastebin.com.

I've tried to work out what your code says in the two comments, but can't figure it out.