Hello to all, haven't been on here in a while but recently been having major problems with trying to finish this second problem set my teacher has given me and the other students for the gr. 12 ics college coarse, currently im gr. 11 but this coarse had to be a filler for my math being switched to 2nd period. any way, the problem is that we have just started to do file opening, reading, writing, and other stuff related to files, my problem is that im on the second question now and were supposed to make a file before hand for this program called "studentAges.txt", that have student ages in random order (I have it from 12 to 20, like so: 12, 20, 19, 17, 14, 13, 15, 18, 16), and get the program to read those ages in, put them into a list, sort them into ascending order, then append the list and put them into an output file.

here is my code:

file_in=open("studentAges.txt", "r")
file_out=open("StudentAges(Sorted).txt", "w")

ages=file_in.readline()
list1=[]
for x in range (0,11):
ages=file_in.readline()
list1.append(ages)
list1.sort(cmp=None, key=None, reverse=False)
list1.append(ages)
print list1

file_out.write(str(list1))

file_in.close()
file_out.close()

for me though, i think my problem just rests in this part of the code:

for x in range (0,11):
ages=file_in.readline()
list1.append(ages)
list1.sort(cmp=None, key=None, reverse=False)
list1.append(ages)
print list1

i just think there is either something missing or that I'm doing wrong

and this is the end result that i get in the idle shell when after I've told my program to print list1 to show me what went into my output file:

['', '', '', '', '', '13\n', '13\n', '14\n', '14\n', '15\n', '15\n', '16', '16', '17\n', '17\n', '18\n', '18\n', '19\n', '19\n', '20\n', '20\n', '']

It's almost right but the 12 is missing, every thing is being repeated 2 times, and all of them except for 16 has the new line character symbol next to it.

any and all help is appreciated, but i dont want to just be given the answer, im still in school trying to learn =).

thanks in advance,

lucas (my real name..)

Dani AI

Generated

's output shows the classic set of mistakes that produce missing values, duplicates and stray newline characters: the first readline() before the loop consumes the initial 12 and is never appended; range(0,11) hard-codes more iterations than there are lines (so empty strings get read); each iteration appends the same value twice; and sort() is being called inside the loop. Newline characters appear because the raw line strings are not stripped and numeric sorting is not reliable while the values remain strings.

A cleaner, Python-2.4-compatible approach is to: read the file once, detect whether the ages are comma-separated or one-per-line, split into tokens, strip whitespace, filter out empty tokens, convert tokens to integers, sort the integer list once, then write the sorted results. Avoid with (the context manager used in newer examples) since that is not available in 2.4.1; use explicit open() and close() instead.

Example (Python 2.4 compatible):

f = open('studentAges.txt', 'r')
data = f.read()
f.close()

if ',' in data:
    parts = data.split(',')
else:
    parts = data.splitlines()

ages = []
for p in parts:
    s = p.strip()
    if s:
        try:
            ages.append(int(s))
        except ValueError:
            pass

ages.sort()

out = open('StudentAges(Sorted).txt', 'w')
out.write(', '.join([str(a) for a in ages]))
out.close()

Quick debugging tips: print repr() of the tokens to see hidden newlines or spaces, print the token count to verify no extra empty reads, and never both append a value and then append it again in the same iteration. 's concise solution is good for newer Python versions (the with pattern and key=int are handy there), but the code above is tailored for Python 2.4.1 and explains why the original loop produced the observed output.

Recommended Answers

All 2 Replies

Use code tag so indentation works.
You are doing some unnecessary stuff.
The answer is not so long,so i dont break it up.

with open('age.txt') as f:
    for item in f:
        sorted_list = sorted(item.split(','), key=int)

with open('age_out.txt', 'w') as f_out:
    f_out.write(','.join(sorted_list))
    #--> 12, 13, 14, 15, 16, 17, 18, 19, 20

Some point is best to always use with open(),then you dont need to close fileobject.
And with open() is doing some error handling to.
When you read from file and write to file it is string that is used.
Here i dont convert the list to integer and sort,but use key=int to sort the list of string.
Then join that list to a string and write to file.

commented: Elegant one! +12

thing is for your code i dont think works for me because for class were using python 2.4.1 so i think some of the code doesn't work for me and using in this version of python.and im not sure myself how i would go about changing this so that it works in my program... =/

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.