Darth Vagrant
Darth Vagrant

Reputation: 139

Move first file from folder to current directory

I need to move the first file of a folder to my current directory:

import os
import shutil

shutil.move(os.listdir('path to folder')[-1], os.getcwd())

I get the error:

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'name of  the file I want to move'

Could someone point out what I am doing wrong, please?

Thank you!

Upvotes: 0

Views: 888

Answers (1)

Yoiro
Yoiro

Reputation: 352

Well, when I've had to move files I wrote something like this:

for file in os.listdir(self.dlPth):    
    newfile = os.path.join(self.destPth, "name-of-new-file")
    shutil.move(os.path.join(self.dlPth,file), newfile)

destPth is the destination path and dlPth is the one where my file was downloaded.

Can you give the paths you are using? I mean the exact way you are writing them in your code?


EDIT

dl = os.path.join(os.getenv('USERPROFILE'), 'Downloads')
shutil.move(os.path.join(dl, os.listdir(dl)[0]), (dl+"\\test\\"))

listdir[index] will only return a file name, not a path. That's why it can't find the wanted file

Upvotes: 2

Related Questions