Ajeet Yadav
Ajeet Yadav

Reputation: 3

ord() expected a character, but string of length 0 found in python code

Following is my code which I am executing

https://github.com/federico-terzi/gesture-keyboard/blob/master/learn.py

After executing the code I am getting,

File "learn.py", line 57, in

number = ord(category) -ord('a')

TypeError: ord() expected a character, but string of length 0 found

How can I fix it?

Upvotes: 0

Views: 5799

Answers (2)

Bijoy
Bijoy

Reputation: 1131

the project data directory contains many files whose filename starts with _ like _sample_t10_34.txt.

So in your code

for path, subdirs, files in os.walk(root):
    for name in files:
        category = name.split("_")[0] # here category = ''

Now the next line is:

number = ord(category) - ord("a")

here as ord() takes an argument of type str of length 1, you get this error, as category would sometime be an empty string '', when files with name _sample_t10_34.txt is beign read.

what you can do is skip files which starts with _, by checking with an if statement whether the file doesnt starts with _.

for path, subdirs, files in os.walk(root):
    for name in files:
        if not name.startswith('_'):
            # code here after if statement
            category = name.split("_")[0]
            number = ord(category) - ord("a")
            # rest of code..

Upvotes: 0

James
James

Reputation: 36608

Looking at the code you linked to, category comes from

category = name.split("_")[0]

and name comes from:

for path, subdirs, files in os.walk(root):
    for name in files:

So my guess that you have a file name with a leading underscore. Splitting this string on '_' this will give an empty string for the first value of the list. Example:

s = '_abc_test.txt'
s.split('_')
# returns:
['', 'abc', 'test.txt']

The zeroth element of this is an empty string which is getting passed to ord.

Upvotes: 1

Related Questions