I'm trying to make a program that takes questions from a CSV file then asks them but weighted by their score. The lowest scored ones go first.
To do this I have a sort function.
def sort_records(csv_filename, sorted_file):
with open(csv_filename, 'r') as i, open(sorted_file, 'w') as 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 the first time, no problem.
But when there are no more questions to be asked and if the user decides to run the program again, it takes the files that have been written to (new_filename as well as another called answer_file) and deletes the original file and sorted file (file, sorted_file) then renames the updated file (answer_file) to just 'file'
def end(file, updated_file, sorted_file):
ans_ok = False
while ans_ok == False:
ans = input("That's all folks... go again? Y/N: ")
ans.upper()
if ans == 'N':
print("Press Enter to 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 I try to run the main function again it works and subsequently runs the sort_records function with the updated file that had just been renamed but that comes up with:
line 24, in sort_records
writer.writerows(sorted(reader, key=operator.itemgetter(0)))
IndexError: list index out of range
EDIT. This is the 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
with open(newfile) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
rownum+=1
ask_question(row,updated_file,reader,sorted_file,file,rownum)
end(file, updated_file, sorted_file)
Main is the first function called in the program also
UPDATE I have found that by comparing the two files' text outside of notepad, the new file generated by the program looks like this: The text in both files
Notepad did not show this for some reason.
Now I have another question:
How do I write to a CSV file in Python without it automatically putting a blank line in-between lines being written?