简体   繁体   中英

Sorting a list from a file, outputting in another file

I am trying to find the min and max out of a csv file, and have it output into a text file, currently my code outputs all data into the output file, and I am unsure of how to grab the data out of the multiple columns and have them sorted accordingly.

Any guidance would be appreciated, as I don't have a good lead on how to figure this out

read_file = open("riskfactors.csv", 'r')

def create_file():

    read_file = open("riskfactors.csv", 'r')
    write_file = open("best_and_worst.txt", "w")

    for line_str in read_file:
        read_file.readline()
        print (line_str,file=write_file)

    write_file.close()
    read_file.close()

Assuming your file is a standard .csv file containing only numbers separated by semicolons:

1;5;7;6;
3;8;1;1;

Then it's easiest to use the str.split() command, followed by a type conversion to int. You could store all values in a list (or quicker: set) and then get the maximum:

valuelist=[]
for line_str in read_file:
     for cell in line_str.split(";"):
         valuelist.append(int(cell))
print(max(valuelist))
print(min(valuelist))

Warning: If your file contains non-number entries you'd have to filter them out. .csv-files can also have different delimiters.

import sys, csv

def cmp_risks(x, y):
    # This assumes risk factors are prioritised by key columns 1, 3
    # and that column 1 is numeric while column 3 is textual
    return cmp(int(x[0]), int(y[0])) or cmp(x[2], y[2])

l = sorted(csv.reader(sys.stdin), cmp_risks))

# Write out the first and last rows
csv.writer(sys.stdout).writerows([l[0], l[len(l)-1]])

Now, I took a shortcut and said the input and output files were sys.stdin and sys.stdout . You'd probably replace these with the file objects you created in your original question. (eg read_file and write_file )

However, in my case, I'd probably just run it (if I were using linux) with:

$ ./foo.py <riskfactors.csv >best_and_worst.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM