Home > Software engineering >  How can I fix path.join error? It's not accepting the output of a function, even when typecast
How can I fix path.join error? It's not accepting the output of a function, even when typecast

Time:08-07

I'm trying to write a simple script that organises image files based on their label, (given by a separate csv file -- this has been imported as a list called 'trainLabels15list').

import shutil
import os
    
source_dir = '/content/drive/MyDrive/Colab Notebooks/Warner/resized train 15/resized train 15/'

def target():
  for x in trainLabels15list:
    if x[0] == file_name:
      trainLabels15list[x][1]

for file_name in filenames:
    shutil.move(os.path.join(source_dir, file_name), os.path.join(source_dir, target()))

if we print(trainLabels15list), this is what that list looks like:

[['10_left', '0'], ['10_right', '0'], ['13_left', '0'], ['13_right', '0'], .......

if we print(filenames), which is a list of all the files in the folder, this is what that looks like:

['8881_right.jpg', '8874_left.jpg', '8899_left.jpg', '8885_left.jpg', ..........

I keep getting the following error however:

TypeError: join() argument must be str or bytes, not 'NoneType'

I think this is referring to this part of the code: os.path.join(source_dir, target()), because target() is a function? But even if I force the output of target() to be cast into an int, or even string, it doesn't work.

What am I missing here?

CodePudding user response:

Probably you are looking for the in operator and you need to return something from target function.
Reconstructing from your (shrinked example) data:

import shutil
import os

trainLabels15list = [['10_left', '0'], ['10_right', '0'], ['13_left', '0'], ['13_right', '0']]
source_dir = '/content/drive/MyDrive/Colab Notebooks/Warner/resized train 15/resized train 15/'
filenames = ['8813_left.jpg', '8874_left.jpg', '8899_left.jpg', '8885_left.jpg']

def target(file_name):
  # filePattern == '10_left', fileValue == '0' and so on!
  for filePattern, fileValue in trainLabels15list:
    if filePattern in file_name:
      return fileValue

for file_name in filenames:
    targetFilename = target(file_name)
    if targetFilename:
      #shutil.move(os.path.join(source_dir, file_name), os.path.join(source_dir, targetFilename))
      print(os.path.join(source_dir, file_name), '>>>', os.path.join(source_dir, targetFilename))

Out:

/content/drive/MyDrive/Colab Notebooks/Warner/resized train 15/resized train 15/8813_left.jpg >>> /content/drive/MyDrive/Colab Notebooks/Warner/resized train 15/resized train 15/0
  • Related