I have a file containing one column with values:

I want to sort this data. I tried to use sort() directly on my raw data but I get error message saying 'str' object has no attribute 'sort'.

I now it's basic, but I'm a beginner at Python and now I don't know how to proceed.

Recommended Answers

All 9 Replies

sorted(data, key=float)

I still get a error message saying could not convert string to float.

My code looks like this:

f = open('data', 'r')
f_data = f.readlines()
for lines in f_data:
    d = sorted(lines, key=float)

line 5 only:

with open('data.txt') as data:
    d = sorted(data, key=float)

Little more sure way as float does not like empty input.

>>> with open('data.txt') as data:
...     d = sorted(data, key=float)
Traceback (most recent call last):
  File "<console>", line 2, in <module>
ValueError: empty string for float()
>>> with open('data.txt') as data:
...     d = sorted((d.rstrip() for d in data if d != '\n'), key=float)
>>> d
['.769', '1.00', '1.345', '3.258']

I don't understand for d in data if d != '\n' and also, why can't I use a for loop like I first did? Do you have to use with ?

Also is it possible after getting this list

['.769', '1.00', '1.345', '3.258']

to get back to the way I had the data from the beginning (see below)?


Of course you can use your f_data as well, instead of my data, and keep it to have the original order available without rereading the file. with statement is the officially recommended way to handle files, otherwise you could use try...except...finally explicitely. On the other hand current implementations with right kind of garbage collection algorithms, let you even open the file and not close it properly as garbage collector will close it when reclaiming the memory.

ok, thanks for your help! But what if I would want to use the with argument, then i end up with this list.

Is it possible to get back to the way my data looked from the beginning?

Just save it:

with open('data.txt') as infile:
     data = [float(item) for item in infile if item.rstrip()] # or normal for loop
     sorted_data = sorted(data)

This way we keep calculable numbers in list.

It's working now! Thanks!

Be a part of the DaniWeb community

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