How to move files listed in a text file from one folder to another in python

Question:

I’m attempting too create a script in Python that reads through a text file. On each line of the text file, there’s a file name. I want the script to cycle through each line of the text file and move the file with the file name from the current line it’s cycled on, from it’s source folder to a specific destination.

Hopefully this code gives a more accurate idea as to what I’m trying to do:

import shutil

dst = "C:\Users\Aydan\Desktop\1855"

with open('1855.txt') as my_file:
    for line in my_file:
        src = "C:\Users\Aydan\Desktop\data01\BL\ER\D11\fmp000005578\" + line
        shutil.move(src, dst)

I was thinking of putting the contents of the file with the specific file names into an array, but I have 62700+ possible file names to end up with, so I was thinking if it just moved the files as it cycled onto every line that it would be a tad more efficient?

I also had the idea of using an iterator (or whatever you call it) setting i=[number of lines in the text file], then make it scroll that way, but seeing as if used for line in my_file: I thought it would make sense to use just line.

For a test, the text file contains:

BL_ER_D11_fmp000005578_0001_1.txt
BL_ER_D11_fmp000005578_0002_1.txt
BL_ER_D11_fmp000005578_0003_1.txt

The problem I’m having with this code is that it’s not working as intended, I don’t get any errors but the movement of files from one folder to another isn’t happening. I would like it if you guys could possible point out a solution to this problem.

Thanks!

Aydan

Asked By: Aydan Howell

||

Answers:

I would try:

import os

dst = "C:\Users\Aydan\Desktop\1855\" # make sure this is a path name and not a filename

with open('1855.txt') as my_file:
    for filename in my_file:
        src = os.path.join("C:\Users\Aydan\Desktop\data01\BL\ER\D11\fmp000005578\", filename.strip() ) # .strip() to avoid un-wanted white spaces
        os.rename(src, os.path.join(dst, filename.strip()))
Answered By: Shai

Using
.strip()
while providing destination path is solving this issue

import shutil
dst = r"C:/Users/Aydan/Desktop/1855/"

with open('test.txt') as my_file:
    for filename in my_file:
        file_name  = filename.strip()
        src = r'C:/Users/Aydan/Desktop/data01/BL/ER/D11/fmp000005578/'+ file_name    
        shutil.move(src, dst + file_name)
Answered By: Suraj

The script works if there are no subfolders. But, if I need to move files inside the subfolders, this does not work. How to modify so that it will also move files inside subfolder to destination folder?

Answered By: user20231823
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.