Python Syntax error while execution - python

I am getting a syntax error for the line below i am not sure why this error is getting generated as earlier it used to work fine and suddenly it started throwing this error
myfile.write('\n'+str(serverAndInstance)+','+str(GCOverHead)+','+str(min(usedAfterGc))+','+str(max(usedAfterGc))+','+str(sum(usedAfterGc)/len(usedAfterGc))+',0,0')

Your line, as posted, works just fine, which means that the preceding line is missing a closing ), ] or } parenthesis, bracket or brace:
>>> something = (something_else + str(whatever)
... myfile.write('\n'+str(serverAndInstance)+','+str(GCOverHead)+','+str(min(usedAfterGc))+','+str(max(usedAfterGc))+','+str(sum(usedAfterGc)/len(usedAfterGc))+',0,0')
File "<stdin>", line 2
myfile.write('\n'+str(serverAndInstance)+','+str(GCOverHead)+','+str(min(usedAfterGc))+','+str(max(usedAfterGc))+','+str(sum(usedAfterGc)/len(usedAfterGc))+',0,0')
^
SyntaxError: invalid syntax
Here it is the something line that is missing a closing parenthesis (2 times ( but only one )) but Python won't know it is missing until parsing the next line.
You really should use the csv module instead to write comma-separated values to a file, your line would be a lot more readable if you used:
with open(outputfile, 'wb') as outfh:
csvwriter = csv.writer(outfh)
for something in some_iterable:
# ...
row = [serverAndInstance, GCOverHead, min(usedAfterGc), max(usedAfterGc),
sum(usedAfterGc) / len(usedAfterGc), 0, 0]
csvwriter.writerow(row)

Related

Trying to make a log function

I want to make a log function in my script but I don`t know why it gives me this error
File "c:/Users/x/x/x", line 33
log = open(f"Log/{realDate.strftime("%x")}.txt", "a")
^
SyntaxError: invalid syntax
Here`s the code that is causing the problem
realDate = datetime.datetime.now()
log = open(f"Log/{realDate.strftime("%x")}.txt", "a")
log.write("Hello Stackoverflow!")
log.close()
Can somebody please help me?
The problem is that you are trying to nest double quotes inside double quotes; f-strings don't allow that. You would need to change one or the other to another style of quotes. For example:
log = open(f'Log/{realDate.strftime("%x")}.txt', "a")
The main problem is that you aren't using a version of Python that supports f-strings. Make sure you are using Python 3.6 or later. (Update: Even in Python 3.6 or later, the identified location of the error can shift:
>>> f"{print("%x")}"
File "<stdin>", line 1
f"{print("%x")}"
^
SyntaxError: invalid syntax
>>> f"{print("x")}"
File "<stdin>", line 1
f"{print("x")}"
^
SyntaxError: invalid syntax
)

Getting a SyntaxError when trying out "with" in Python3.6

When attempting to open an existing text file (myfile.txt) with "with":
with open ('myfile.txt') as my_new_file:
I get the following error:
File "<ipython-input-263-06288b4ea914>", line 1
with open ('myfile.txt') as my_new_file:
^
SyntaxError: unexpected EOF while parsing
However, I am able to open the file using "open":
myfile = open('myfile.txt')
myfile.read()
'Hello, This is a text file\nThis is the second line\nThis is the third line'
Can someone point out what it is that I am doing wrong? Thanks!
Alls you need to do is do something after the colon. Finish the thought.
$ python -c "with open ('myfile.txt') as my_new_file:"
File "<string>", line 1
with open ('myfile.txt') as my_new_file:
^
SyntaxError: unexpected EOF while parsing
$ python -c "with open ('myfile.txt') as my_new_file: print(my_new_file.readlines())"
['hey\n', 'you\n']
An EOF error is an unexpected End Of File error where, the Python interpreter was expecting something part of the with statement on the next line.
For example:
with open ('myfile.txt') as my_new_file:
my_new_file.read()
is valid. Since the with statement has something in it, whereas:
with open ('myfile.txt') as my_new_file:
my_new_file.read()
Will return an error since there is nothing part of the with, when there should be at least one function in order to use the flow control.
If you have nothing to do then you should call pass. This has nothing to do with the file you want to read. Exactly the same effect can be made by using any statement that requires an indent, without the indent:
for i in range(100):
print('Hello')

How to open and read a file in Python?

All I am trying to do is get Python to open and read a file I have created. I realize there are many other ways to do this, but I'm just wondering why this isn't working. I have my file saved in the same location as this as well. Does python recognize rec for records? I just watched a tutorial on this so I'm rather confused
with open('Broncos.txt') as fo:
for rec in fo:
print rec
Syntax Error: print rec: <string>, line 6, pos 17
The syntax error you're receiving is most likely due to the lack of parentheses around your print statement (assuming you're using Python 3). A simple change will allow the program to run:
with open('Broncos.txt') as fo:
for rec in fo:
print(rec)
I think that error is in the last line of your code. You need to include parenthesis around rec in last line of your code:
with open('Broncos.txt') as fo:
for rec in fo:
print (rec)
Python 2 vs. Python 3: print
Very trivial, and the change in the print-syntax is probably the most
widely known change, but still it is worth mentioning: Python 2’s
print statement has been replaced by the print() function, meaning
that we have to wrap the object that we want to print in parantheses.
Python 2 doesn’t have a problem with additional parantheses, but in
contrast, Python 3 would raise a SyntaxError if we called the print
function the Python 2-way without the parentheses.
So you'd need to do this:
with open('Broncos.txt') as fo:
for rec in fo:
print(rec)

Opening a file and matching Engr Label

1.Getting buildid from a buildlocation which is the last word after "\" which is "A1234ABCDE120083.1" in this case
2.After getting the buildid,am opening a file and then trying to match the line "Engr Label: Data_CRM_PL_177999" to get the label name which is "Data_CRM_PL_177999"
3.Final output should be "Data_CRM_PL_177999"
For some reason I am getting the following syntax error..
import re
Buildlocation= '\\umor\locations455\INT\A1234ABCDE120083.1'
Labelgetbuildlabel(Buildlocation)
def getbuildlabel(BuildLocation):
buildid=BuildLocation.split('\')[-1]
Notes=os.path.join(BuildLocation,Buildid + '_notes.txt')
if os.path.exists(Notes):
try:
open(Notes)
except IOError as er:
pass
else:
for i in Notes.splitlines:
if i.find(Engr Label)
label=i.split(:)[-1]
print label//output should be Data_CRM_PL_177999
Output should be:-
Line looks like below in the file
Engr Label: Data_CRM_PL_177999
SYNTAX ERROR
buildid=BuildLocation.split('\')[-1]
^
SyntaxError: EOL while scanning string literal
In the line
buildid=BuildLocation.split('\')[-1]
The backslash is actually escaping the following quotation mark
So, Python thinks this is actually your string:
'[-1])
Instead, you should do the following:
buildid=BuildLocation.split('\\')[-1]
And Python will interpret your string to be
\\
Interestingly, StackOverflow's syntax highlighter hints at this issue. If you look at your code, it treats everything after that first slash as part of the string, all the way to the end of your code sample.
You also have a few other issues in your code, so I tried cleaning it up a bit for you. (However, I don't have a copy of the file, so obviously, I wasn't able to test this)
import re
import os.path
build_location= r'\\umor\locations455\INT\A1234ABCDE120083.1'
label = get_build_label(build_location)
# Python prefers function and variable names to be all lowercase with
# underscore separating words.
def get_build_label(build_location):
build_id = build_location.split('\\')[-1]
notes_path = os.path.join(build_location, build_id + '_notes.txt')
# notes_path is the filename (a string)
try:
with open(notes_path) as notes:
# The 'with' keyword will automatically open and close
# the file for you
for line in notes:
if line.find('Engr Label'):
label = line.split(':')[-1]
return label
except IOError:
# No need to do 'os.path.exists' since notes_path doesn't
# exist, then the IOError exception will be raised.
pass
print label
The backslash is escaping the ' character (see the escape codes documentation)
Try this line instead:
buildid=BuildLocation.split('\\')[-1]
Now you have a backslash escaping the backslash, so your string is a literal backslash. The other thing you could do would be to tell Python that this string doesn't have any escape codes by prefixing it with an r like this:
buildid=BuildLocation.split(r'\')[-1]
You've got a number of other problems as well.
The comment character in Python is #, not //.
I think you're also confusing a filename with a file object.
Notes is the name of the file you're trying to open. Then, when you call open(Notes), you will get back a file object that you can read data from.
So you should probably replace:
open(Notes)
with
f = open(Notes)
And then replace:
for i in Notes.splitlines:
with
for line in f:
When you do a for loop over a file object, Python will automatically give you a line at a time.
Now you can check each line like this:
if line.find("Engr Label") != -1:
label = line.split(':')[-1]

NameError. Might be eval(), raw_input, or misunderstanding

Working with Python 2.6 and receiving an annoying error, and I'm still unsure why. My file of interest contains multiple lines of only a single value. I want to retrieve these values. This snippet of code
f = open(file, 'r')
for line in file:
value = eval(line)
results in the following error message:
File "<string>", line 1, in <module>
NameError: name 'c' is not defined
So I researched here on Stack Overflow.. with this question and another one.. but I'm having trouble drawing connections between their problems and mine. What I got from them is that my use of eval() may be confusing Python and I should use raw_input to let Python know that it doesn't have to evaluate line but rather the actual variables line represents. However, fixing my code to be:
for line in file:
value = eval(raw_input(line))
Which kicked out the following error (and may have overloaded terminal.. it simply froze up until I quit the program):
File "<string>", line 0
^
SyntaxError: unexpected EOF while parsing
What am I doing wrong here? I've picked up the fact that eval() isn't the favorite to use around SO, am I misunderstanding it's function?
EDIT: My file is a list of values so,
2
3
2
3
1
0
etc
EDIT So it was a misunderstanding. Thank you to DSM for pointing out my file names being mismatched and to Levon for still helping out and showing int as a better alternative to eval.
If you just want to read those numbers from a file and convert them to integers this will do.
with open('data.txt') as f:
for line in f:
value = int(line)
Then you can use the value as needed.
Aside: The advantage of using with to open the file is that it is automatically closed for you when you are done, or an exception is encountered.
To respond to the title of your question, yes you are misunderstanding it. Let me explain:
eval executes the code you place in it. So x=eval('c') is the same as x=c.
raw_input is used to get user input. The parameter is the string to display to the user, not the input.
If you just want to read the values that are in a file, you could use
with open('file') as f:
for line in f:
var = int(line)
if you want to retrieve values from the files then this will do, using eval() for this doesn't make sense:
>>> with open('data.txt') as f:
values=[int(x) for x in f]
>>> values
[2, 3, 2, 3, 1, 0]

Categories