I am trying to do this exercise but fail. I can only get this result:
main() File "C:\Users\chemuser\Desktop\KHL\python\chapter4_6.py", line 22, in main
asciimark = eval(line) File "<string>", line 1
^ SyntaxError: unexpected EOF while parsing
here is my fail code:
# -*- coding: cp1252 -*-
#A certain CS professor gives 5-point quizzes that are
#graded on the scale 5-A, 4-B, 3-C, 2-D, 1-F, 0-F.
#Write a program that accepts a quiz score as an
#input and prints out the corresponding grade.
import string
def main():
#set up file names
infileName = raw_input("input file name: ")
outfileName = raw_input("output file name: ")
#open files
infile = open(infileName, "r")
outfile = open(outfileName, "w")
#process each line of the input file
for line in infile.readlines():
#get the mark from line
asciimark = eval(line)
#creat grade
allgrade = "FEDCBA"
grade = allgrade[asciimark]
#write it to the output file
outfile.write(grade+"\n")
#close both files
infile.close()
outfile.close()
print "Done!"
main()
the input file is look like this (just a column of number 0 - 5, no blank line between):
5
1
0
2
3
I did a test, I add '/n' in the first line (5/n), it shows:
main() File "C:\Users\chemuser\Desktop\KHL\python\chapter4_6.py", line 22, in main
asciimark = eval(line) File "<string>", line 1
5\n
^ SyntaxError: unexpected character after line continuation character
your comments are very appreciated!!
Related
Importing is behaving inconsistently and I'm pretty sure it's because of my meta_path loader.
My importer
class JaPyCodeImporter(object):
def __init__(self, modules):
self._modules = {}
self._last_module = None
modules = dict(modules)
for key in modules:
module_info = {}
module_info["full_name"] = key
module_info["source"] = modules[key]
module_info["code"] = compile(modules[key], key, "exec")
module_info["is_package"] = False
module_info["package"] = key.rpartition('.')[0]
if not key.rfind("__init__") == -1:
module_info["full_name"] = key[:key.rfind(".__init__")]
module_info["is_package"] = True
module_info["package"] = module_info["full_name"]
self._modules[module_info["full_name"]] = module_info
self._last_path = ""
def find_module(self, fullname, path):
if fullname in self._modules.keys():
print("Found: {0}".format(fullname))
return self
elif self._last_module and self._last_module["package"] + "." + fullname in self._modules.keys():
print("Found: {0} in package {1}".format(fullname, self._last_module["package"]))
return self
print("Couldn't find: {0}".format(fullname))
pdb.traceback.print_stack()
return None
def load_module(self, fullname):
expanded_name = self._last_path + "." + fullname
# check for pre-existence
if fullname in sys.modules:
return sys.modules[fullname]
elif self._last_module and self._last_module["package"] + "." + fullname in sys.modules:
return sys.modules[self._last_module["package"] + "." + fullname]
# check internally
if not fullname in self._modules.keys():
if self._last_module and not self._last_module["package"] + "." + fullname in self._modules.keys():
raise ImportError(fullname)
else:
fullname = self._last_module["package"] + "." + fullname
module_info = self._modules[fullname]
new_module = sys.modules.setdefault(fullname, imp.new_module(fullname))
new_module.__loader__ = self
new_module.__file__ = "<%s>" % self.__class__.__name__
new_module.__path__ = [] #module_info["package"].split(".")
new_module.__package__ = module_info["package"]
print("Loaded: {0}".format(module_info["full_name"]))
try:
self._last_module = self._modules[fullname]
print("Execute: {0}".format(module_info["full_name"]))
globals()["__name__"] = module_info["full_name"]
globals()["__package__"] = module_info["package"]
exec(self._modules[fullname]["code"], globals(), new_module.__dict__)
except SyntaxError as err:
error_class = err.__class__.__name__
detail = err.args[0]
line_number = err.lineno
print("%s at line %d of %s: %s" % (error_class, line_number, description, detail))
del sys.modules[fullname]
return None
except Exception as err:
error_class = err.__class__.__name__
detail = err.args[0]
print(detail)
cl, exc, tb = sys.exc_info()
line_number = traceback.extract_tb(tb)[-1][1]
print("%s at line %d of %s: %s" % (error_class, line_number, fullname, detail))
del sys.modules[fullname]
return None
return new_module
My file structure
gameSystem/
__init.__py
interface_bridge.py
libraries/
__init__.py
standard/
__init__.py
area.py
base_object.py
exit.py
player.py
Start of interface_bridge.py
print("*** begin interface_bridge.py ***")
# from https://github.com/jython/jython/blob/0a58cc26566d2b2334e80b2b3f2f42f6c738db2d/lib-python/2.7/ihooks.py
# line 424
print("__name__: {0}".format(globals()['__name__']))
# line 418
print("__package__: {0}".format(globals()['__package__']))
print("Begin imports")
import pickle
import io
import sys
print(dir(sys.modules[__name__]))
from . libraries.standard.player import Player
print(Player)
from . libraries.standard.player import Player # <- Line 22
#from . libraries.standard.area import Area
Yep, I'm literally trying to import Player a second time directly after the first. I'm doing that because I can see from the output that Player is imported correctly the first time. Regardless, if I use the second Player import or the commented Area import, the output is the same.
The output
*** begin interface_bridge.py ***
__name__: gameSystem.interface_bridge
__package__: gameSystem
Begin imports
Couldn't find: gameSystem.pickle
File "<iostream>", line 236, in loadGameData
File "<iostream>", line 116, in load_module
File "gameSystem.interface_bridge", line 13, in <module>
File "<iostream>", line 66, in find_module
Couldn't find: gameSystem.io
File "<iostream>", line 236, in loadGameData
File "<iostream>", line 116, in load_module
File "gameSystem.interface_bridge", line 14, in <module>
File "<iostream>", line 66, in find_module
Couldn't find: gameSystem.sys
File "<iostream>", line 236, in loadGameData
File "<iostream>", line 116, in load_module
File "gameSystem.interface_bridge", line 15, in <module>
File "<iostream>", line 66, in find_module
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', 'io', 'pickle', 'sys']
Found: gameSystem.libraries
Loaded: gameSystem.libraries
Execute: gameSystem.libraries
Found: gameSystem.libraries.standard
Loaded: gameSystem.libraries.standard
Execute: gameSystem.libraries.standard
Found: gameSystem.libraries.standard.player
Loaded: gameSystem.libraries.standard.player
Execute: gameSystem.libraries.standard.player
<class 'gameSystem.libraries.standard.player.Player'> <- Player class loaded!
Couldn't find: gameSystem.libraries.standard.libraries
File "<iostream>", line 236, in loadGameData
File "<iostream>", line 116, in load_module
File "gameSystem.interface_bridge", line 22, in <module>
File "<iostream>", line 66, in find_module
Couldn't find: gameSystem.libraries.standard.libraries
File "<iostream>", line 236, in loadGameData
File "<iostream>", line 116, in load_module
File "gameSystem.interface_bridge", line 22, in <module>
File "<iostream>", line 66, in find_module
No module named gameSystem.libraries.standard.libraries
ImportError at line 22 of gameSystem.interface_bridge: No module named gameSystem.libraries.standard.libraries
Those first three couldn't finds (pickle, io, and sys) all make sense as they are Python libraries (though it's interesting to see them being treated as if their part of the gameSystem package). My importer shouldn't handle them and kicks them back to the import system.
Then, as I interpret it, the import system starts working down the package structure (.libraries, .libraries.standard) to finally get to gameSystem.libraries.standard.player, which is loaded and executed without problem. You can see the class is ready to go as it can be printed to the output <class '...Player'>.
What happens next is where I get confused. Why is it trying to import gameSystem.libraries.standard.libraries? Why two times in a row?
I'm fairly certain this is caused by some mistake I've made in my importer but I'm baffled. I would expect both import lines to behave exactly the same way.
I am learning Python.
For code:
def main():
fileName = raw_input("file name ")
infile = open(fileName, "r")
sm = 0.0
ct = 0
line = infile.readline()
while line != "":
sm = sm + eval(line)
ct = ct + 1
line = infile.readline()
print "\nAverage is ", sm/ct
main()
it results the following error:
Traceback (most recent call last):
File "/home/sorin/avg6.py", line 13, in <module>
main()
File "/home/sorin/avg6.py", line 8, in main
sm = sm + eval(line)
File "<string>", line 1
^
SyntaxError: unexpected EOF while parsing
I don't understand way. Please help. Thank you.
The eval function expects the string you pass it to be a valid Python expression, but it got an empty string (or, given the while loop's condition, perhaps a string with only whitespace). That doesn't have a value, so it raises an error.
You may want to look in the data file to see if there any blank lines (and remove them, if you can). Or you could modify the code to ignore invalid strings:
while line != "":
try:
sm = sm + eval(line)
ct = ct + 1
except SyntaxError:
pass
line = infile.readline()
You might also want to catch other kinds of errors, if you go that route.
Another option is to explicitly check for specific invalid strings that might come up (like just a bare newline):
while line != "":
if line != "\n": # or maybe us "if line.strip()", to reject whitespace lines
sm = sm + eval(line)
ct = ct + 1
line = infile.readline()
One final suggestion is to use a for loop on the file object rather than a while loop with calls to readline. This won't prevent the kinds of error you're getting, but it generally results in nicer looking code, which might be easier to debug.
What does your input file look like? If your input file has a blank line, it would explain your error.
I’m trying to program a simple code in python that will overwrite my existing file and also add one to every value or line in my file.
For example my “num.txt” file:
5 ---> 6
7 ---> 8
9 ---> 10
11 ---> 12
13 ---> 14
file = raw_input("Enter filename: ")
infile = open(file,'r')
for line in infile:
value = int(line)
infile.write(str(value + 1))
infile.truncate()
infile.close()
Error message:
infile.write(str(value + 1))
IOError: File not open for writing
I really appreciate your help
Thx
Geno
Your file is not open for writing, this line
infile = open(file,'r')
means that open the file for reading.
If you want to open the file for writing, you can use 'w' (write) or 'r+' (read and write) use this instead:
infile = open(file,'r+')
for more you can read (http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python) --> Mode Section.
If you use 'r+' the code should be something like
infile = open(file, 'r+')
for line in infile:
val = int(line)
infile.write(str(val + 1) + '\n')
infile.truncate()
infile.close()
But I suppose this wont serve the purpose which you want to do, this will just append the values to the end. If you want to write these new values to file, use this instead:
infile = open(file, 'r')
lines = infile.readlines() #this gives a list of all lines
infile.close()
outfile = open(file, 'w') #erases previous contents
for line in lines:
outfile.write(str(int(line) + 1) + '\n') #if you are sure file have int's only
outfile.close()
For Python 3,
filename = input("Enter filename: ")
with open(filename, 'r+') as file:
lines = file.readlines()
file.seek(0)
for line in lines:
value = int(line)
file.write(str(value + 1))
file.truncate()
I have an input file like:
input.txt:
to
the
cow
eliphant
pigen
then
enthosiastic
I want to remove those words which has character length is <= 4 , and if some word has more than 8 character then write those word in new file till 8 character length
output should be like:
output.txt:
eliphant
pigen
enthosia
This is my code:
f2 = open('output.txt', 'w+')
x2 = open('input.txt', 'r').readlines()
for y in x2:
if (len(y) <= 4):
y = y.replace(y, '')
f2.write(y)
elif (len(y) > 8):
y = y[0:8]
f2.write(y)
else:
f2.write(y)
f2.close()
print "Done!"
when i compile it then it gives the output like:
eliphantpigen
then
enthosia
it also writes 4 character length word... i don't understand what is the problem and how to write the code to limit character length of text file words....?
Use with when working with files, this guarantees that file would be closed.
You have then in your results because your are reading lines and not worlds.
Each line have symbol of ending '\n'. So when you are reading world then you have string
'then\n' and len of this string is 5.
with open('output.txt', 'w+') as ofp, open('input.txt', 'r') as ifp:
for line in ifp:
line = line.strip()
if len(line) > 8:
line = line[:8]
elif len(line) <= 4:
continue
ofp.write(line + '\n')
i have a text file with some site links.... i want to remove the string which is before the site name.
here is the input file >>
input.txt:
http://www.site1.com/
http://site2.com/
https://www.site3333.co.uk/
site44.com/
http://www.site5.com/
site66.com/
output file should be like:
site1.com/
site2.com/
site3333.co.uk/
site44.com/
site5.com/
site66.com/
here is my code:
bad_words = ['https://', 'http://', 'www.']
with open('input.txt') as oldfile, open('output.txt', 'w') as newfile:
for line in oldfile:
if not any(bad_word in line for bad_word in bad_words):
newfile.write(line)
print './ done'
when i run this code then it totally remove the lines which containing bad_words
site44.com/
site66.com/
what should i do with code to get my specific result?
Thanks all i have solved this... code should be:
fin = open("input.txt")
fout = open("output.txt", "w+")
delete_list = ['https://', 'http://', 'www.']
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
fin.close()
fout.close()
print './ done'