Aydan Howell
Aydan Howell

Reputation: 75

How to open a folder loop through opening other files within that folder in python

This current question is building on from this question.

I am trying to create a python script that will loop through all the text files in the specified folder. The text files contain directories to files that will be moved to a different specified folder. When looping through a text file, it takes the file from the file directory on each line of that text file.

The end goal is to have all the files which are referenced in the text file to move into one specified folder (\1855).

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

with open(r'C:\Users\Aydan\Desktop\RTHPython\Years') as my_folder:
    for filename in my_folder:
        text_file_name = filename.strip()
        with open (text_file_name) as my_file:
            for filename in my_file:
                file_name  = filename.strip()
                src = r'C:\Users\Aydan\Desktop' + file_name    
                shutil.move(src, dst)

One text file (1855.txt) contains:

/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0001_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0002_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0003_1.txt

and another text file (1856.txt) contains:

/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0004_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0005_1.txt
/data01/BL/ER/D11/fmp000005578/BL_ER_D11_fmp000005578_0006_1.txt

This is the error I get when I run the above script:

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    with open(r'C:\Users\Aydan\Desktop\RTHPython\Years') as my_folder:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Aydan\\Desktop\\RTHPython\\Years'

This script doesn't seem to be moving the files named here to the C:/Users/Aydan/Desktop/1855 destination, even though in the script I'm trying to follow the same logic of iterating through each item in the text file, but applying that logic to a folder instead of inside text file.

Any help to find a solution would be brilliant! If you need any more info about the files just ask.

Thanks!

Aydan.

Upvotes: 2

Views: 1136

Answers (1)

Lucy The Brazen
Lucy The Brazen

Reputation: 137

Since you can't open whole folders with the open method, you can get cycle through every .txt file in that folder like that:

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

for filename in glob.glob(r"C:\Users\Aydan\Desktop\RTHPython\Years\*.txt"):
    text_file_name = filename.strip()
    with open (text_file_name) as my_file:
        for filename in my_file:
            file_name  = filename.strip()
            src = r'C:\Users\Aydan\Desktop' + file_name    
            shutil.move(src, dst)

Upvotes: 1

Related Questions