+ 1
What's wrong with my code?
file = open("Test.txt") cont = file.read print (cont) file.close Why does this raise an SyntaxError in the first line??? Help please I am going crazy. Even if I write file = open("Test.txt", "r") it raises the same Error... Why?
46 Antworten
+ 8
Yes, try to avoid naming variables like reserved keywords or builtins. In some cases it might confuse the interpreter. Idk if this is the case, but just for the __future__ ;)
+ 8
😉
+ 7
Bjarne Sohns I think u forgot a colon at the definiton of the function
(for the code u posted in the comments)
+ 7
ffllfl = open("Test.txt","w")
ffllfl.write ("Hello World!")
ffllfl.close()
ffllfl=open("Test.txt","r")
cont = ffllfl.read()
print (cont)
ffllfl.close()
+ 7
working now?
+ 7
are u trying it on sololearn
+ 7
or maybe it has something to do with your version of python? are you using python 3
+ 7
maybe for PC u need the files location on the pc, I don't know but try creating a .txt file using notepad store it somewhere and copy the location from the address bar it will probably be like:
ffllfl=open("c://........"r")
cont = ffllfl.read()
print (cont)
ffllfl.close()
try that if it also doesn't work then @Kuba you're up next sir
+ 7
sorry for not being able to help
+ 6
You have to add a colon at the end of the first line and an ending parentheses in the last one.
+ 6
Why don't you open the file in write mode, write sth to it then read it?
+ 6
https://code.sololearn.com/cOXugcl6onVm/?ref=app
did something similar here
+ 6
on the fifth line make it ffllfl=open("Test.text",'r') instead of ffllfl.open. It'll work after that.
+ 5
I ran this in Sololearn, changing the open() argument to __file__, so it wouldn't break down. All goes well if you add parentheses.
+ 5
@Bjarne have you tried copying my code and running it?
file = open(__file__) #there are double floors there
cont = file.read()
print (cont)
file.close()
+ 5
Then I don't know...
Maybe it's the variable name which is also a builtin?
Try changing it to f
+ 4
cont = file.read()
file.close()
Have a nice day 😊
+ 4
No, I added a self-reference to the code:
file = open(__file__)
cont = file.read()
print (cont)
file.close()
+ 4
Go ahead, we are all here to learn and help each other.
Try saving it to a code on SL though. It is much easier to comment on the code you see and can run instantly.