Reputation: 4398
i had created a python program but it was not working. this program would take in the input for a file and then display the file contents . the only error i was getting is a syntax error well i could not find the error . Please help me . the code was :-
nm = input(“enter file name “)
str = raw_input(“enter ur text here: \n”)
f = open(nm,”w”)
f.write(str)
f.close()
print “1.See the file\n”
print “2.Exit\n”
s = input(“enter ur choice “)
if s == 1 :
fi = open(nm,”r”)
cont = fi.read()
for i in cont:
print i
else :
print “thank you “
Upvotes: 0
Views: 1757
Reputation: 3770
The problem is that you are reading the filename using input()
instead of raw_input()
. See this answer that explains:
If you use input, then the data you type is is interpreted as a Python Expression which means that you end up with gawd knows what type of object in your target variable, and a heck of a wide range of exceptions that can be generated. So you should NOT use input unless you're putting something in for temporary testing, to be used only by someone who knows a bit about Python expressions.
raw_input always returns a string because, heck, that's what you always type in ... but then you can easily convert it to the specific type you want, and catch the specific exceptions that may occur. Hopefully with that explanation, it's a no-brainer to know which you should use.
Also, since you are reading in the file contents by using fi.read()
, your for loop for i in cont:
will select each character of the file's contents one at a time, instead of each line. Something to be aware of!
Upvotes: 2