YoungCoder YoungCoder - 21 days ago 3
Python Question

Why can't I move just my text files to different folder in Python?

I am using the Python shutil module to move 4 txt files from FolderA to FolderB.

When I run the following code I get a trace-back error:

shutil.move('C:\Users\Student\Desktop\FolderA.txt', 'C:\Users\Student\Desktop\FolderB')


But I know that pathway does in fact exist because when I try this command it works fine and moves the whole Folder A(including txt files) into FolderB:

shutil.move('C:\Users\Student\Desktop\FolderA', 'C:\Users\Student\Desktop\FolderB')


Any way to move just the text files without just copying them? I am using Python Shell 2.7 in case you wanted to know.

Answer

1st, escape the path separator correctly, either use double backslash or add a r'' in front to indicate its raw string like below

this command is not doing what you intended, it try to move file call FolderA.txt into FolderB

shutil.move(r'C:\Users\Student\Desktop\FolderA.txt', r'C:\Users\Student\Desktop\FolderB')

code below should do what you intended. Use glob module to grep all txt file in FolderA then move them 1 by 1 into FolderB

import glob
# this will move all txt file from FolderA into FolderB
# but you need to ensure FolderB exists, else it might create a file named FolderB instead
for f in glob.glob(r'C:\Users\Student\Desktop\FolderA\*.txt'):
    shutil.move(f, r'C:\Users\Student\Desktop\FolderB')
Comments