Python3 split () not enough values to unpack (expceted 2, got 1)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.