elif(ch==2):
fh=open("emp1.txt","rb+")
fo=open("temp.txt","wb+")
ecode=input("Enter the Ecode :")
rec=(" ")
try:
while True:
emp1= pickle.load(fh)
if (emp1.ecode!=ecode):
pickle.dump(emp1,fh)
except(EOFError):
fh.close()
fo.close()
os.remove("empl.txt")
os.rename("temp.txt","emp1.txt")
print("")
running the following code gives me this error:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 78,
in
emp1= pickle.load(fh) EOFError
During handling of the above exception, another exception occurred:
Traceback (most recent call last): File
"C:\Users\hello\Desktop\bhavi\python programming\Employ.py", line 85,
in
os.remove("empl.txt") FileNotFoundError: [WinError 2] The system cannot find the file specified: 'empl.txt'
What should i do now??
You should fix your path. In the first case, you write "emp1.txt"; and in the second, you write "empl.txt". If you look carefully, you should notice that there is a difference in those two strings.
Hint: '1' != 'l'
Your code could probably be refactored as well. While it is not possible for others to test your code since it is very incomplete, the following should work in its place. You will still need to verify it works.
elif ch == 2:
with open('emp1.txt', 'rb+') as fh, open('temp.txt', 'wb+') as fo:
ecode = input('Enter the Ecode: ')
while True:
try:
item = pickle.load(fh)
except EOFError:
break
else:
if item.ecode != ecode:
pickle.dump(item, fo)
os.remove(fh.name)
os.rename(fo.name, fh.name)
print()
I would use shelve, its much easier to use and it doesn't come up with to many errors in my experience. shelve is built on pickle but it just simplify it.
here is a short tutorial
http://python.wikia.com/wiki/Shelve
Related
I am working on a very basic problem on Hackerrank.
Input format:
First line contains integer N.
Second line contains string S.
Output format:
First line should contain N x 2.
Second line should contain the same string S.
sample test case
5
helloworld
my code is as: (on PYTHON 3)
n=int(input())
s=input()
print(2*n)
print(s)
I am getting error:
Execution failed.
EOFError : EOF when reading a line
Stack Trace:
Traceback (most recent call last):
File "/tmp/143981299/user_code.py", line 1, in <module>
N = int(input())
EOFError: EOF when reading a line
I tried this method to take input many times and this is the first time I am having this error. Can anyone please explain why?
use a try/except block to handle the error
while True:
try:
n=int(input())
s=input()
print(2*n)
print(s)
except:
break
I am creating a program that lets you launch applications from Python. I had designed it so if a certain web browser was not downloaded, it would default to another one. Unfortunately, the try block seems to only function with one 'except FileNotFoundError.' Is there any way to have multiple of these in the same try block? Here's my (failing) code below:
app = input("\nWelcome to AppLauncher. You can launch your web browser by typing '1', your File Explorer by typing '2', or quit the program by typing '3': ")
if app == "1":
try:
os.startfile('chrome.exe')
except FileNotFoundError:
os.startfile('firefox.exe')
except FileNotFoundError:
os.startfile('msedge.exe')
If the user does not have Google Chrome downloaded, the program attempts to launch Mozilla Firefox. If that application is not found, it should open Microsoft Edge; instead it raises this error in IDLE (Please note that I have purposely misspelled chrome.exe and firefox.exe in order to simulate the programs essentially not existing):
Traceback (most recent call last):
File "C:/Users/NoName/AppData/Local/Programs/Python/Python38-32/applaunchermodule.py", line 7, in <module>
os.startfile('chome.exe')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'chome.exe'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:/Users/NoName/AppData/Local/Programs/Python/Python38-32/applaunchermodule.py", line 9, in <module>
os.startfile('frefox.exe')
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'frefox.exe'
Is there any way to raise two of the same exceptions in a single try block?
for exe in ['chrome.exe','firefox.exe','msedge.exe']:
try:
os.startfile(exe)
break
except FileNotFoundError:
print(exe,"error")
For your exact case, I would suggest this:
priority_apps = ['chrome.exe', 'firefox.exe', 'msedge.exe'] # attempts to open in priority order
current_priority = 0
opened_app = False
while not opened_app and current_priority < len(priority_apps):
try:
os.startfile(priority_apps[current_priority])
opened_app = True
except Exception as e:
current_priority += 1
if not opened_app:
print("couldn't open anything! :(")
generic alternative with functions:
try:
do_something()
except Exception as e:
do_something_else1()
def do_something_else1():
try:
do_something()
except Exception as e:
do_something_else2()
generic alternative with nested try/except:
try:
do_something()
except Exception as e:
try:
do_something_else()
except Exception as e:
do_something_better()
I am a newbie to programming and I tried to do some interesting stuffs and ended up here, while string tokenizing I encountered this error while I can't solve this atmost
code:
import re
def cw(text):
counts=dict()
text=text.lower()
words=re.split(r'[^\w]',text)
for i in words:
print(words)
if i !="":
if i not in words:
counts[i]=1
else:
counts[i]+=1
return counts
def input():
with open("input.txt",'r') as f:
text=f.read()
counts=cw(text)
sort=sorted(counts.items(),key=lambda pair: pair[1],reverse=True)
print(sort)
if __name__ == "__main__":
input()
Error is:
Traceback (most recent call last):
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 35, in <module>
input()
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 27, in input
counts=cw(text)
File "C:/Users/surya/AppData/Local/Programs/Python/Python37-32/okay.py", line 17, in cw
counts[i]+=1
KeyError: 'as'
Question-
https://www.codechef.com/problems/SINS
Compiler used-
https://www.codechef.com/ide
Input method-
Custom input of codechef compiler.
My attempt-
T=int(input())
def fnc(a,b):
if b!=0:
return fnc(b,a%b)
else:
return int(a*2)
while T>0:
X,Y=map(int,input().split())
if X==0:
print(Y)
elif Y==0:
print(X)
elif X==Y:
print(X*2)
else:
f=fnc(X,Y)
print(f)
T=T-1
Issue:
I am getting the following runtime error:
Traceback (most recent call last):
File "./prog.py", line 8, in <module>
EOFError: EOF when reading a line
The output is correct but still there is this runtime error.
That is because the input() is getting End Of File (I assume you are using Python 3). You need to trap the EOFError exception and break out of the loop when you get it. You asked what I meant by that comment, this is what I mean:
try:
X, Y = map(int, input().split())
except EOFError:
break
I am using Python 3.3 through the IDLE. While running a code that looks like:
raise KeyError('This is a \n Line break')
it outputs:
Traceback (most recent call last):
File "test.py", line 4, in <module>
raise KeyError('This is a \n Line break')
KeyError: 'This is a \n Line break'
I would like it to output the message with the line break like this:
This is a
Line Break
I have tried to convert it to a string before or using os.linesep but nothing seems to work. Is there any way I can force the message to be correctly shown on the IDLE?
If I raise an Exception (instead of KeyError) then the output is what I want, but I would like to still raise a KeyError if possible.
You problem has nothing to do with IDLE. The behavior you see is all from Python. Running current repository CPython interactively, from a command line, we see the behavior you reported.
Python 3.7.0a2+ (heads/pr_3947:01eae2f721, Oct 22 2017, 14:06:43)
[MSC v.1900 32 bit (Intel)] on win32
>>> raise KeyError('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'This is a \n Line break'
>>> s = 'This is a \n Line break'
>>> s
'This is a \n Line break'
>>> print(s)
This is a
Line break
>>> raise Exception('This is a \n Line break')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
Exception: This is a
Line break
>>> raise IndexError(s)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: This is a
Line break
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e)
'This is a \n Line break'
>>> try:
... raise KeyError('This is a \n Line break')
... except KeyError as e:
... print(e.args[0])
This is a
Line break
I don't know why KeyError acts differently from even IndexError, but printing e.args[0] should work for all exceptions.
EDIT
The reason for the difference is given in this old tracker issue, which quotes a comment in the KeyError source code:
/* If args is a tuple of exactly one item, apply repr to args[0].
This is done so that e.g. the exception raised by {}[''] prints
KeyError: ''
rather than the confusing
KeyError
alone. The downside is that if KeyError is raised with an
explanatory
string, that string will be displayed in quotes. Too bad.
If args is anything else, use the default BaseException__str__().
*/
This section appears in the KeyError_str object definition in Objects/exceptions.c of the Python source code.
I will mention your issue as another manifestation of this difference.
There is a way to get the behavior you want: Simply subclass str and override __repr__:
class KeyErrorMessage(str):
def __repr__(self): return str(self)
msg = KeyErrorMessage('Newline\nin\nkey\nerror')
raise KeyError(msg)
Prints:
Traceback (most recent call last):
...
File "", line 5, in
raise KeyError(msg)
KeyError: Newline
in
key
error