this question has answer here:
i'm trying make program takes questions csv file asks them weighted score. lowest scored ones go first.
to have sort function.
def sort_records(csv_filename, sorted_file): open(csv_filename, 'r') i, open(sorted_file, 'w') o: reader = csv.reader(i, delimiter = ',') writer = csv.writer(o, delimiter=',') writer.writerow(next(reader)) # header row writer.writerows(sorted(reader, key=operator.itemgetter(0)))
this works first time, no problem.
but when there no more questions asked , if user decides run program again, takes files have been written (new_filename called answer_file) , deletes original file , sorted file (file, sorted_file) renames updated file (answer_file) 'file'
def end(file, updated_file, sorted_file): ans_ok = false while ans_ok == false: ans = input("that's folks... go again? y/n: ") ans.upper() if ans == 'n': print("press enter exit...") input(" ") ans_ok = true elif ans == 'y': os.remove(file) os.remove(newfile) os.rename(updated_file,file) print("\n ok!\n") main()
and when try run main function again works , subsequently runs sort_records function updated file had been renamed comes with:
line 24, in sort_records writer.writerows(sorted(reader, key=operator.itemgetter(0))) indexerror: list index out of range
edit. main function calling both of these
def main(): path_ok = false while path_ok == false: try: file = input("subject file: ") sorted_file = file[:-4]+'_sorted.sar' sort_records(file,sorted_file) path_ok = true except ioerror: print("\tfile not found. please input valid filename or path") updated_file = sorted_file[:-4]+'_final.sar' rownum = 0 open(newfile) csvfile: reader = csv.dictreader(csvfile) row in reader: rownum+=1 ask_question(row,updated_file,reader,sorted_file,file,rownum) end(file, updated_file, sorted_file)
main first function called in program also
update have found comparing 2 files' text outside of notepad, new file generated program looks this: the text in both files
notepad did not show reason.
now have question:
how write csv file in python without automatically putting blank line in-between lines being written?
ok, sorted. turns out case, story on :)
second question answered by: why csv file contain blank line in between each data line when outputting dictwriter in python
thanks stackoverflow!
Comments
Post a Comment