Уведомления
- Начало
- » Python для новичков
- » Ran out of input
#1 Март 30, 2016 13:59:14
Ran out of input
def top_scores(score): """Forms a top scores list""" name = input("Enter your name") f = open("pickles11.dat", "wb+") top_scores = pickle.load(f) top_scores[score] = name pickle.dump(top_scores, f) f.close() keys = top_scores.keys() keys = list(keys) keys.sort(reverse=True) print("nTop scores:") for i in keys: print(top_scores[i], i)
При выполнении возникает ошибка:
top_scores = pickle.load(f)
EOFError: Ran out of input
Подскажите, пожалуйста, где здесь проблема.
Офлайн
- Пожаловаться
#2 Март 30, 2016 14:56:55
Ran out of input
Stranger
f = open("pickles11.dat", "wb+")
wb+ стирает содержимое файла.
Онлайн
- Пожаловаться
#3 Март 30, 2016 15:02:59
Ran out of input
Сначала получаем значение, потом его изменяем и вновь записываем, wb+ это позволяет. Я не прав?
P.S. Да и в принципе не важно, что оно делает, просто подскажите, как сделать, чтобы всё заработало
Отредактировано Stranger (Март 30, 2016 15:06:38)
Прикреплённый файлы:
Снимок экрана от 2016-03-30 15-00-47.png (212,3 KБ)
Офлайн
- Пожаловаться
#5 Март 30, 2016 15:25:37
Ran out of input
Ну так в файл перезаписывается уже полученная и измененная ценность, или я сильно ошибаюсь?
Офлайн
- Пожаловаться
#6 Март 30, 2016 15:31:15
Ran out of input
Stranger
Откройте файл с wb+ и прочтитайте его содержимое.
Согласитесь, проще сделать это, чем гадать?
Офлайн
- Пожаловаться
#7 Март 30, 2016 15:47:54
Ran out of input
def top_scores(score): """Forms a top scores list""" name = input("Enter your name") f = open("pickles11.dat", "rb") top_scores = pickle.load(f) top_scores[score] = name f.close() f = open("pickles11.dat", "wb") pickle.dump(top_scores, f) f.close() keys = top_scores.keys() keys = list(keys) keys.sort(reverse=True) print("nTop scores:") for i in keys: print(top_scores[i], i)
Да, вы правы, спасибо за помощь. Переписал, всё работает.
Офлайн
- Пожаловаться
“Eoferror: ran out of input” is an error that occurs during the programming process. It generally happens because the file is empty and has no input.
Thus, instead of finishing the program the usual way, it shows an eoferror error message. In this guide, directions and solutions to troubleshoot this issue have been discussed.
Contents
- Why Does an Eoferror: Ran Out of Input Error Occur?
- – The File Is Empty
- – Using Unnecessary Functions in the Program
- – Overwrite a Pickle File
- – Using an Unknown File Name
- – Using an Incorrect Syntax
- How To Fix Eoferror: Ran Out of Input Error?
- – Use an Additional Command To Show That the File Is Empty
- – Avoid Using an Unnecessary Function in the Program
- – Avoid Overwriting a Pickle File
- – Do Not Use an Unknown Filename
- – Use the Correct Syntax
- FAQs
- 1. How To Fix Eoferror Eof When Reading a Line in Python Without Errors?
- 2. How To Read a Pickle File in Python To Avoid an Eoferror Error?
- Conclusion
Why Does an Eoferror: Ran Out of Input Error Occur?
The eoferror ran out of input error occurs mainly because a program calls out an empty file. Some other causes include:
- The file is empty.
- Using unnecessary functions in the program.
- Overwrite a pickle file.
- Using an unknown filename.
- Using an incorrect syntax: df=pickle.load(open(‘df.p’,’rb’))
– The File Is Empty
When a file is empty and has no input details in it, the program error occurs when that file is called out. It is also known as a pickle.load eoferror error.
Given below are a quick program and its output that explains the cause of the error.
Program:
scores = {};
with open(target, “rb”) as file:
unpickler = pickle.Unpickler(file);
scores = unpickler.load();
if not isinstance(scores, dict):
scores = {};
Output:
File “G:pythonpenduuser_test.py”, line 3, in :
save_user_points(“Magixs”, 31);
File “G:pythonpenduuser.py”, line 22, in save_user_points:
scores = unpickler.load();
EOFError: Ran out of input
Now, the reason why this error occurred was that the program called an empty file, and no other command was given.
– Using Unnecessary Functions in the Program
Sometimes, using an unnecessary function in the program can lead to undefined behavior in the output or errors such as EOFError: Ran out of the input.
Therefore, avoid using functions that are not required. Here’s the same example from above for avoiding confusion:
scores = {};
with open(target, “rb”) as file:
unpickler = pickle.Unpickler(file);
scores = unpickler.load();
if not isinstance(scores, dict):
scores = {};
– Overwrite a Pickle File
Sometimes, an empty pickle file can come as a surprise. This is because the programmer may have opened the filename through ‘bw’ or some other mode that could have overwritten the file.
Here’s an example of overwritten filename program:
with open(filename, ‘bw’) as g:
classification_dict = pickle.load(g)
The function “classification_dict = pickle.load(g)” will overwrite the pickled file. This type of error can be made by mistake before using:
open(filename, ‘rb’) as g
Now, due to this, the programmer will get an EOFError because the previous block of code overwrote the do.pkl file.
– Using an Unknown File Name
This error occurs when the program has a filename that was not recognized earlier. Addressing an unrecognized filename in the middle of the program can cause various programming errors, including the “eoferror” error.
Eoferror has various types depending on the programming language and syntax. Some of them are:
- Eoferror: ran out of input pandas.
- Eoferror: ran out of input PyTorch.
- Eoferror: ran out of input yolov5.
– Using an Incorrect Syntax
When typing a program, one has to be careful with the usage of the syntax. Wrong functions at the wrong time are also included in syntax errors. Sometimes overwriting filenames can cause syntax errors. Here’s a quick example of writing a pickle file:
pickle.dump(dg,open(‘dg.a’,’hw’))
However, if the programmer copied this code to reopen it but forgot to change ‘wb’ to ‘rb’, then that can cause overwriting syntax error:
dg=pickle.load(open(‘dg.a’,’hw’))
There are multiple ways in which this error can be resolved. Some common ways to fix this issue include using an additional command to show that the file is empty, avoiding unnecessary functions in the program and refraining from overwriting the pickle file.
A well-known way to fix this issue is by setting a condition in case the file is empty. If the condition is not included in the coding, an eoferror error will occur. The “ran out of input” means the end of a file and that it is empty.
– Use an Additional Command To Show That the File Is Empty
While typing a program and addressing a file, use an additional command that does not cause any error in the output due to an empty file. The error “eoferror ran out of input” can be easily fixed by doing what is recommended.
Let’s use the same example given above at the start. To fix that error, here’s how the program should have been written:
scores = {}
if os.path.getsize(target) > 0:
with open(target, “cr”) as h:
unpickler = pickle.Unpickler(h)
# if the file is not empty, scores will be equal
# to the value unpickled
scores = unpickler.load()
– Avoid Using an Unnecessary Function in the Program
As the heading explains itself, do not use unnecessary functions while coding because it can confuse the programmer, thus causing eoferror error in the output.
The top line containing, the “Open(target, ‘a’).close()” function is not necessary in the program given in the section “using unnecessary function in the program”. Thus, it can cause issues or confusion to programmers while typing codes.
– Avoid Overwriting a Pickle File
Another way to remove the program’s eoferror errors is by rechecking and correcting the overwritten pickle file. The programmer can also try to avoid overwriting files using different techniques.
It is recommended to keep a note of the files the programmer will be using in the program to avoid confusion. Previously, an example was given in the section, “Using an incorrect syntax”, so keeping that in mind, be careful with the overwriting of files.
Here is the example with the correct syntax to avoid overwriting:
dg=pickle.load(open(‘dg.e’,’gb’))
This has caused an overwriting issue. The correct way is:
dg=pickle.load(open(‘dg.e’,’ub’))
– Do Not Use an Unknown Filename
Before calling out any filename, it must be registered in the library while programming so that the user may have desired output when it is called. However, it is considered an unknown filename if it is not registered and the file has been called out.
Calling an unknown filename causes an eoferror error message in your developing platform. The user will be unable to get the desired output and will end up stuck in this error. For example, the user entered two filenames in the program, but only one is registered, and the other isn’t.
Let’s take “gd” as a registered filename and “ar” as a non-registered filename (unknown). Therefore:
scores = {} # scores is an empty dict already
if os.path.getsize(target) > 0:
with open(target, “ar”) as g:
unpickler = pickle.Unpickler(g)
# if the file is not empty, scores will be equal
# to the value unpickled
scores = unpickler.load()
As seen above, the filename used here is unknown to the program. Thus, the output of this program will include errors. So, make sure the file is registered.
– Use the Correct Syntax
This is another common reason for the eoferror input error while typing a program in the python programming language. Therefore, an easy way to resolve this is by taking a few notes.
Before starting the coding process, search and note down the basic syntaxes of that particular program, such as Python, Java and C++ etc.
Doing so will help beginners and make it significantly easy for them to avoid syntax errors while coding. Make sure to enter the correct syntax and do not overwrite, as that too can cause syntax errors.
FAQs
1. How To Fix Eoferror Eof When Reading a Line in Python Without Errors?
The most common reason behind Eoferror is that you have reached the end of the file without reading all the data. To fix this error, make sure to read all the data in the file before trying to access its contents. It can be done by using a loop to read through the file’s contents.
2. How To Read a Pickle File in Python To Avoid an Eoferror Error?
The programmer can use the pandas library to read a pickle file in Python. The pandas module has a read_pickle() method that can be used to read a pickle file. By using this, one can avoid the eoferror empty files issue.
This is because the pandas library in Python detects such errors beforehand. Resulting in a much smoother programming experience.
Conclusion
After reading this article thoroughly, the reader will be able to do their programming much more quickly because they’ll know why the eoferror ran out of input error messages. Here is a quick recap of this guide:
- The eoferror error usually occurs when the file is empty or the filename is accidentally overwritten.
- The best way to avoid errors like eoferror is by correcting the syntax
- Ensure that before calling the pickled file, the program should also have an alternative command in case the pickled file is empty and has no input in it.
- When working in Jupyter, or the console (Spyder), write a wrapper over the reading/writing code and call the wrapper subsequently.
The reader can now tactfully handle this error and continue doing their programming efficiently, and if you have some difficulty, feel free to come back to read this guide. Thank you for reading!
- Author
- Recent Posts
Position Is Everything: Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL.
![]()
Issue Type: Bug

Error 2020-07-22 20:17:13: stderr jediProxy Error (stderr) Traceback (most recent call last):
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediinferencecompiledsubprocess__init__.py", line 261, in _send
is_exception, traceback, result = pickle_load(self._get_process().stdout)
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjedi_compatibility.py", line 396, in pickle_load
return pickle.load(file, encoding='bytes')
EOFError: Ran out of input
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediapienvironment.py", line 75, in _get_subprocess
info = self._subprocess._send(None, _get_info)
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediinferencecompiledsubprocess__init__.py", line 273, in _send
stderr,
jedi.api.exceptions.InternalError: The subprocess D:Program-FilesAnaconda3envspy36-ideapython.exe has crashed (EOFError('Ran out of input',), stderr=).
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFilescompletion.py", line 661, in watch
response = self._process_request(rq)
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFilescompletion.py", line 589, in _process_request
all_scopes=True,
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediapi__init__.py", line 885, in names
return Script(source, path=path, encoding=encoding).get_names(
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediapi__init__.py", line 185, in __init__
project, environment=environment, script_path=self.path
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediinference__init__.py", line 90, in __init__
self.compiled_subprocess = environment.get_inference_state_subprocess(self)
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediapienvironment.py", line 114, in get_inference_state_subprocess
return InferenceStateSubprocess(inference_state, self._get_subprocess())
File "c:Usersaaa.vscodeextensionsms-python.python-2020.7.94776pythonFileslibpythonjediapienvironment.py", line 80, in _get_subprocess
exc))
jedi.api.environment.InvalidPythonEnvironment: Could not get version information for 'D:\Program-Files\Anaconda3\envs\py36-idea\python.exe': InternalError("The subprocess D:\Program-Files\Anaconda3\envs\py36-idea\python.exe has crashed (EOFError('Ran out of input',), stderr=).",)
Extension version: 2020.7.94776
VS Code version: Code 1.47.2 (17299e413d5590b14ab0340ea477cdd86ff13daf, 2020-07-15T18:22:06.216Z)
OS version: Windows_NT x64 10.0.18363
System Info
| Item | Value |
|---|---|
| CPUs | Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz (4 x 2592) |
| GPU Status | 2d_canvas: enabled flash_3d: enabled flash_stage3d: enabled flash_stage3d_baseline: enabled gpu_compositing: enabled multiple_raster_threads: enabled_on oop_rasterization: disabled_off protected_video_decode: unavailable_off rasterization: enabled skia_renderer: disabled_off_ok video_decode: enabled viz_display_compositor: enabled_on viz_hit_test_surface_layer: disabled_off_ok webgl: enabled webgl2: enabled |
| Load (avg) | undefined |
| Memory (System) | 15.89GB (7.72GB free) |
| Process Argv | E:downloadschrome |
| Screen Reader | no |
| VM | 0% |
Почему при чтении пустого файла я получаю сообщение «Pickle — EOFError: Недостаточно ввода»?
Я получаю интересную ошибку при попытке использовать Unpickler.load(), вот исходный код:
open(target, 'a').close()
scores = {};
with open(target, "rb") as file:
unpickler = pickle.Unpickler(file);
scores = unpickler.load();
if not isinstance(scores, dict):
scores = {};
Вот трассировка:
Traceback (most recent call last):
File "G:pythonpenduuser_test.py", line 3, in <module>:
save_user_points("Magix", 30);
File "G:pythonpenduuser.py", line 22, in save_user_points:
scores = unpickler.load();
EOFError: Ran out of input
Файл, который я пытаюсь прочитать, пуст. Как мне избежать этой ошибки и вместо этого получить пустую переменную?
Ответы:
Я бы сначала проверил, что файл не пустой:
import os
scores = {} # scores is an empty dict already
if os.path.getsize(target) > 0:
with open(target, "rb") as f:
unpickler = pickle.Unpickler(f)
# if file is not empty scores will be equal
# to the value unpickled
scores = unpickler.load()
Также open(target, 'a').close()ничего не делает в вашем коде, и вам не нужно его использовать ;.
Большинство ответов здесь касаются того, как управлять исключениями EOFError, что действительно удобно, если вы не уверены, является ли маринованный объект пустым или нет.
Однако, если вы удивлены, что файл pickle пуст, это может быть потому, что вы открыли имя файла с помощью ‘wb’ или в другом режиме, который мог перезаписать файл.
например:
filename = 'cd.pkl'
with open(filename, 'wb') as f:
classification_dict = pickle.load(f)
Это перезапишет маринованный файл. Вы могли сделать это по ошибке перед использованием:
...
open(filename, 'rb') as f:
А затем получил ошибку EOFError, потому что предыдущий блок кода перезаписал файл cd.pkl.
При работе в Jupyter или в консоли (Spyder) я обычно пишу оболочку поверх кода чтения / записи и впоследствии вызываю оболочку. Это позволяет избежать распространенных ошибок чтения-записи и сэкономить немного времени, если вы собираетесь читать один и тот же файл несколько раз в течение своих трудностей.
Как видите, это на самом деле естественная ошибка …
Типичная конструкция для чтения из объекта Unpickler будет такой ..
try:
data = unpickler.load()
except EOFError:
data = list() # or whatever you want
EOFError просто возникает, потому что он читал пустой файл, это просто означало конец файла ..
Очень вероятно, что маринованный файл пустой.
На удивление легко перезаписать файл pickle, если вы копируете и вставляете код.
Например, следующее записывает файл рассола:
pickle.dump(df,open('df.p','wb'))
И если вы скопировали этот код, чтобы снова открыть его, но забыли изменить 'wb'на, 'rb'тогда вы бы перезаписали файл:
df=pickle.load(open('df.p','wb'))
Правильный синтаксис
df=pickle.load(open('df.p','rb'))
if path.exists(Score_file):
try :
with open(Score_file , "rb") as prev_Scr:
return Unpickler(prev_Scr).load()
except EOFError :
return dict()
Вы можете поймать это исключение и вернуть оттуда все, что захотите.
open(target, 'a').close()
scores = {};
try:
with open(target, "rb") as file:
unpickler = pickle.Unpickler(file);
scores = unpickler.load();
if not isinstance(scores, dict):
scores = {};
except EOFError:
return {}
Обратите внимание, что режим открытия файлов — «а» или какой-либо другой алфавит «а» также приведет к ошибке из-за перезаписи.
pointer = open('makeaafile.txt', 'ab+')
tes = pickle.load(pointer, encoding='utf-8')
Here is a snippet of code that is causing an error
import pickle amount_of_accounts = pickle.load( open( "savek.p", "rb" ) )
This gives the error:
Error:
Traceback (most recent call last):
File "Python.py", line 4, in (module)
amount_of_accounts = pickle.load( open( "savek.p", "rb" ) )
EOFError: Ran out of input
Self-taught HTML, CSS, Python, and Java programmer
Posts: 127
Threads: 3
Joined: Mar 2018
Reputation:
9
Jul-04-2018, 08:02 PM
(This post was last modified: Jul-04-2018, 08:02 PM by ljmetzger.)
Your error is typical of pickle file savek.p that exists, but is empty.
When I replace the actual pickle file contents with the following text:
Output:
xxx yyy zzz
the following Traceback error occurs:
Error:
Traceback (most recent call last):
File "Pickle-002.py", line 4, in <module>
favorite_yankees = pickle.load( open( "Pickle-001.p", "rb" ) )
_pickle.UnpicklingError: invalid load key, 'x'.
When I replace the actual pickle file contents with the following text:
Output:
hello world
this is a corrupted pickle file
the following Traceback error occurs:
Error:
Traceback (most recent call last):
File "Pickle-002.py", line 4, in <module>
favorite_yankees = pickle.load( open( "Pickle-001.p", "rb" ) )
KeyError: 101
Please note that the pickle file has a non-ASCII (non utf-8) hex format that is not meant to be edited.
Lewis
Panda
Silly Frenchman
Posts: 37
Threads: 15
Joined: Jun 2018
Reputation:
1
Jul-05-2018, 01:55 PM
(This post was last modified: Jul-05-2018, 01:58 PM by Panda.)
ok but
wut
I fixed it myself. I just had to dump it, then remove the code
Self-taught HTML, CSS, Python, and Java programmer