You're missing a closing parenthesis on the line above it.
Python SyntaxError when using open() [closed]
-
10-07-2023 - |
Question
For some reason I keep getting a syntax error from my open statement:
def printStatsToFile():
global dictionary
statslines = []
if dictionary=={}:
createDictionary()
for n in dictionary:
statslines.append("Key = " + str(n) + " Total number of words with " + str(n) + " characters = " + str(len(dictionary[n]))
open(statsWords.dat, "w").writelines(statslines)
print "Your stats are now available in statsWords.dat."
mainFunction()
Here is the error:
tog:hw4 lukasolson$ python hw4_lukasolson.py
File "hw4_lukasolson.py", line 61
open(statsWords.dat, "w").writelines(statslines)
^
SyntaxError: invalid syntax
Oddly, when I comment out part of the code, everything works absolutely fine:
def printStatsToFile():
statslines = []
"""
global dictionary
if dictionary=={}:
createDictionary()
for n in dictionary:
statslines.append("Key = " + str(n) + " Total number of words with " + str(n) + " characters = " + str(len(dictionary[n]))
"""
open("statsWords.dat", "w").writelines(statslines)
print "Your stats are now available in statsWords.dat."
mainFunction()
And I am running python 2.7.6 so as far as I know, my syntax should be correct.
tog:hw4 lukasolson$ python
Python 2.7.6rc1 (v2.7.6rc1:4913d0e9be30+, Oct 27 2013, 20:52:11)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
Solution
OTHER TIPS
You need to pass in statsWords.dat
as a string. Thus, the line should look like:
open("statsWords.dat", "w").writelines(statslines)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow