Home > database >  Loop through subfolder move only specific file to another folder using python
Loop through subfolder move only specific file to another folder using python

Time:07-13

I want to loop between these subfolders and move only http.log file to another folder.

target_folder = new_folder_with_http
source_folder = original_data

for path, dir, files in os.walk(source_folder):
if files == 'http.log':
os.move(target_folder):
else skip

please help me with this code

CodePudding user response:

If your goal is only to find a single http.log file somewhere in the source folder and move it to the target folder, you can use pathlib.Path.glob() to do the work of finding, then just move the first one it finds:

import pathlib

target_folder = pathlib.Path('new_folder_with_http')
source_folder = pathlib.Path('original_data')

found_files = list(source_folder.glob('**/http.log'))

found_files[0].rename(target_folder / 'http.log')

CodePudding user response:

files is a list; you want to check if this file name is a member.

target_folder = new_folder_with_http

for path, dir, files in os.walk(original_data):
    if "http.log" in files:
        os.rename(
            os.path.join(path, "http.log"),
            os.path.join(target_folder, "http.log"))

There is no os.move; I guess you want os.rename or perhaps shutil.move.

Notice also how we need to prefix the path (the directory it was found in) back in front of the bare file name.

The else clause is optional; just don't put one if you don't have any code to put there.

The same file name can only exist once in targetdir so this will fail on Windows if it finds multiple files with the same name. On Unix, or if you switch to shutil.move, it will replace all the found files in targetdir with the last one found. If you don't want either of those things to happen, you'll have to specify a way to make each file name unique after moving, perhaps by renaming it to reflect which directory it was found in somehow.

  • Related