Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

moving a file in python using shutil

Tags:

python

shutil

I know there have been some posts on how to move a file in python but I am a little confused. I am working on a program that has a file called test.txt

The file path is this: C:\Users\user\Desktop\Project1\Project1
I want to move it to: C:\Users\user\Documents\ProjectMoved
I tried different variations of what I have below

src="C:\\Users\\user\\Desktop\\Project1\\Project1\\test.txt"
dst="C:\\Users\\user\\Documents\\ProjectMoved"
shutil.move(src, dst)

I keep getting the error no such file in directory.

I was wondering if someone could help me out with the correct way to move the file.

like image 341
csciBeginner Avatar asked May 18 '26 02:05

csciBeginner


1 Answers

Might be worth checking the file exists and then trying to specify paths using os.path.join:

import shutil
import os
from os.path import join

src = join('/', 'Users', 'username', 'Desktop', 'a.pdf')
dst = join('/', 'Users', 'username', 'Documents', 'a.pdf')

shutil.move(src, dst)

You can first verify if the src actually exists:

os.path.exists(src)
>>> True
like image 150
p-robot Avatar answered May 19 '26 15:05

p-robot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!