When running a small script, the script reads the data from a text file, in fact the file has only one line of ' count:2 ' and takes this 2 and turns it into a number. But run, always error.
The code is as follows:
1With open ('Count.txt','R') as file:2 if notfile.readline ():3 Pass4 Else:5Name, Count = File.readline (). Split (':')6count = Int (count)Code
The error message is as follows:
‘‘‘
Traceback (most recent):
File "C:\Users\Andy\Desktop\split_error.py", line 6, <module>
count = Int (count)
#ValueError: Invalid literal for int. () with base 10: '
‘‘‘
From this you can see that count is empty. But obviously there is content, how can it be empty? The comment goes to count = Int (count), which runs again and goes wrong.
The error message is as follows:
‘‘‘
Traceback (most recent):
File "C:\Users\Andy\Desktop\split_error.py", line 5, <module>
Name, Count = File.readline (). Split (': ')
Valueerror:not enough values to unpack (expected 2, got 1)
‘‘‘
Say is not give enough value to unpack, there should be two, only give one. This is strange, still do not understand the reason.
So the shell interviewed, and finally found the reason:
When the file is opened, such as for a file executed: ReadLines () or ReadLine () then the current position of the file offset will change, readlines () is offset to the end of the file, and Readlin () offset to the next line.
(This script is executed if ReadLines (), not established, and Readlin () in else) is executed.
So, when you call ReadLines () or Readlin () for the second time here,
has reached the end of the file, read the content is empty, so the empty content to take the split (': ') method, of course, error.
Therefore, the best solution here is to offset the file back to the file header before the first read
The method is as follows: File.seek (0)
Read again, everything is OK!
Python3 split () not enough values to unpack (expceted 2, got 1)