ics
ics

Reputation: 51

Python read list from file

I'm trying to sort a list from a file, but I'm getting this error:

Traceback (most recent call last):
  File "/Users/MacbookPro/Documents/Faculta/alg sortare pyth/bubble.py", line 13, in <module>
    f = file.open('lista.txt', 'r')
AttributeError: type object 'file' has no attribute 'open'

This is my code:

from timeit import default_timer as timer
import resource
start = timer()
def bubbleSort(alist):
    for passnum in range(len(alist)-1,0,-1):
        for i in range(passnum):
            if alist[i]>alist[i+1]:
                temp = alist[i]
                alist[i] = alist[i+1]
                alist[i+1] = temp


f = file.open('lista.txt', 'r')
long_string = f.readline()
my_list = long_string.split(',')
bubbleSort(alist)
print(alist), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1000
end = timer()
print(end - start)

Upvotes: 2

Views: 178

Answers (2)

Bilal Ch
Bilal Ch

Reputation: 378

Replace this line:

f = file.open('lista.txt', 'r')

with this one:

f= open('lista.txt', 'r')

Upvotes: 0

Stephen Rauch
Stephen Rauch

Reputation: 49822

To open a file use:

f = open('lista.txt', 'r')

Use a context manager instead:

with open('lista.txt', 'r') as f:
    long_string = f.readline()
    my_list = long_string.split(',')
    ....

The context manager approach will automatically close the file. This especially true when writing a file, but is best practice here also.

Upvotes: 2

Related Questions