kirvoss
kirvoss

Reputation: 13

Programmaticallly moving files in python

I'm trying to simply move files from folder path1 to folder path.

import os
import shutil
path1 = '/home/user/Downloads'
file_dir = os.listdir(path1)
fpath = '/home/user/music'
for file in file_dir:
    if file.endswith('.mp3'):
        shutil.move(os.path.join(file_dir,file), os.path.join(fpath, file))

... but I get this error

TypeError: expected str, bytes or os.PathLike object, not list

Upvotes: 0

Views: 132

Answers (3)

neuro
neuro

Reputation: 15210

Read carefully the error message. file_dir is list. You can not join it with os.path.join. You probably want to write:

shutil.move(os.path.join(path1, f), os.path.join(fpath, f))

I suggest to name variables with meaningful names like:

file_list = os.listdir(path1)

This way you will not join a file list with a path :)

Upvotes: 0

Prune
Prune

Reputation: 77910

You have confused your variable purposes from one line to the next. You've also over-built your file path construction.

You set up file_dir as a list of all the files in path1. That works fine through your for command, where you iterate through that list. The move method requires two file names, simple strings. Look at how you construct your file name:

os.path.join(file_dir,file)

Remember, file_dir is a list of files in path1. file is one of the files in that list. What are you trying to do here? Do you perhaps mean to concatenate path1 with file?

NOTE: Using pre-defined names as variables is really bad practice. file is a pre-defined type. Instead, use f or local_file, perhaps.

Upvotes: 1

wpercy
wpercy

Reputation: 10090

First of all, you shouldn't use file as a variable name, it's a builtin in python, consider using f instead.

Also notice that in the shutil.move line, I've changed your (os.path.join(file_dir,f) to (os.path.join(path1,f). file_dir is a list, not the name of the directory that you're looking for, that value is stored in your path1 variable.

Altogether, it looks like this:

import os
import shutil
path1 = '/home/user/Downloads'
file_dir = os.listdir(path1)
fpath = '/home/user/music'
for f in file_dir:
    if f.endswith('.mp3'):
        shutil.move(os.path.join(path1,f), os.path.join(fpath, f))

Upvotes: 2

Related Questions