'invalid syntax in csv files ipython

these are my input as a csv file but I can not run my code in ipython because of invalid syntax error but I do not know what should I do?

mandana,5,7,3,15
hamid,3,9,4,20,9,1,8,16,0,5,2,4,7,2,1
sina,0,5,20,14
soheila,13,2,5,1,3,10,12,4,13,17,7,7
ali,1,9
sarvin,0,16,16,13,19,2,17,8
def calculate_sorted_averages('C:\Users\Y  A  S  H  E  L\Desktop\in.csv','C:\Users\Y  A  S  H  E  L\Desktop\o.csv'):
    averages = {}
    with open('C:\Users\Y  A  S  H  E  L\Desktop\in.csv') as csv_file:
        csvfile = csv.reader(csv_file, delimiter=',')
        for row in csvfile:
            scores = []
            for i in range(1, len(row)):
                scores.append (float(row[i]))
            avg = mean(scores)
            averages [row[0]] = avg

    averages_ord = OrderedDict (sorted (averages.items(), key=lambda x:(x[1], x[0])))

    with open ('C:\Users\Y  A  S  H  E  L\Desktop\o.csv', 'w') as out:
        count = 0
        for person in averages_ord:
            count += 1
            if count == 1:
                out.write(person+ ","+ str(averages_ord[person]))
            else:
                out.write("\n"+ person+ ","+ str(averages_ord[person]))


Solution 1:[1]

When I copy your function to a python session I get:

    def calculate_sorted_averages('C:\Users\Y  A  S  H  E  L\Desktop\in.csv','C:\Users\Y  A  S  H  E  L\Desktop\o.csv'):
                                  ^
SyntaxError: invalid syntax

You can define a function with

def foo(filename1, filename2):

You can not define it with a literal string, def foo('test.txt'):

A syntax error means your code is wrong at a basic Python syntax level. It doesn't even try to run your code.

This corrects that syntax error. I haven't tried to run it.

def calculate_sorted_averages(file1, file2):
    averages = {}
    with open(file1) as csv_file:
        csvfile = csv.reader(csv_file, delimiter=",")
        for row in csvfile:
            scores = []
            for i in range(1, len(row)):
                scores.append(float(row[i]))
            avg = mean(scores)
            averages[row[0]] = avg

    averages_ord = OrderedDict(sorted(averages.items(), key=lambda x: (x[1], x[0])))

    with open(file2, "w") as out:
        count = 0
        for person in averages_ord:
            count += 1
            if count == 1:
                out.write(person + "," + str(averages_ord[person]))
            else:
                out.write("\n" + person + "," + str(averages_ord[person]))

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1