-2

I test my script just printing return value of .split:

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    print(f_name.split('-'))

and it shows me what I'd like to see - lists with 3 strings in each.

['Earth ', ' Our Solar System ', ' #4']
['Saturn ', ' Our Solar System ', ' #7']
['The Sun ', ' Our Solar System ', ' #1']

However, when I'm trying to store it in 3 different variables:

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_title, f_course, f_num = f_name.split(' - ')

it gives me an error:

f_title, f_course, f_num = f_name.split('-')
    ^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 3, got 1)

I'd appreciate any help on this! Thanks!


  • You've found a file name that _doesn't_ split into three. `print` it before trying to split it to see what that file name is. We can't help you since we don't have access to your files. – Pranav Hosangadi Nov 23 '22 at 16:00
  • I would suggest you to use a print("f_name : {0} - f_ext : {1} \n".format(f_ext, f_name)) That would clarify your doubt – Fedeco Nov 23 '22 at 16:03

2 Answers2

0

What you are experiencing is the diffrence between unpacking three items and a list. What you are getting from f.split is a single item only which is a list of the 'words'

f_name = 'a-b-c'
f_name.split("-") -> [a,b,c] #But a list is a single entity

So consider :

[title,course,num]= f_name.split("-")

However this is not a very good way to do it. What happens if split returns 4 words in a list ? Although this solves your problem, I highly doubt you should be doing it in this way.

Jason Chia
  • 1,144
  • 1
  • 5
  • 18
0

It seems like there are unwanted spaces around the hyphen f_name.split(' - '). Remove them:

for f in os.listdir():
    f_name, f_ext = os.path.splitext(f)
    f_title, f_course, f_num = f_name.split('-')
CodeKorn
  • 300
  • 1
  • 8