Reputation: 50
I am beginner in python . I want to move some files from one directory to another. I just now i have to use some modules like Os and Shutil. and i write this code but it return an error:
import shutil
import os
source = os.listdir("/tmp/")
destination = "/tmp/newfolder/"
for files in source:
if files.endswith(".txt"):
shutil.move(files,destination)
please help me
Upvotes: 2
Views: 7176
Reputation: 82949
This is kind of a wild guess, but I'm pretty sure that this is your problem, so I'll give it a try.
Note that os.listdir
returns a list of filenames only; it does not include the directory that was the parameter to os.listdir
. I.e., you have to tell shutils.move
where to find those files! Also, you might have to create the destination directory, if it does not yet exist. Try this:
import shutil, os
source = "/tmp/"
destination = "/tmp/newfolder/"
if not os.path.exists(destination):
os.makedirs(destination) # only if it does not yet exist
for f in os.listdir(source):
if f.endswith(".txt"):
shutil.move(source + f, destination) # add source dir to filename
Upvotes: 4