MattZ
MattZ

Reputation: 19

Ordering a file

I have this code

archivo=open("archivo.csv","r")
for i in range(10):
    for reg in archivo:
        if archivo[reg] < archivo[reg+1]:
            x = archivo[reg]
            archivo[reg] = archivo[reg+1]
            archivo[reg+1] = x
archivo.close()
archivo = open("archivo.csv","w")
archivo.write(reg)

What i want is to order alphabetically the files and to save it ordered, but i have several errors. The main one says that the file has not atribute getitem and in the web i didn't find anything equal. Can someone help me?

Input looks like

Matt | 7 | 8 
John | 9 | 6 
Jim | 6 | 7

Upvotes: 0

Views: 49

Answers (1)

Supreet Sethi
Supreet Sethi

Reputation: 1806

I have modified the source CSV file to be comma separated. So archivo.csv looks like

Matt,7,8
John,9,6
Jim,6,7

Now to read this file, python already has standard module called csv. Using that we can read and write csv reliably.

from  csv import reader, writer
archivo=reader(open("archivo.csv","r"))
a = sorted(archivo)
archivo1 = writer(open("archivo1.csv", "w"))
for row in a:
    archivo1.writerow(row)

Upvotes: 1

Related Questions