Search code examples
pythonfilefilepathfile-manipulation

Python: How to get the full path of a file in order to move it?


I had files that were in zips. I unzipped them with Zip-7 so they are in folders with the zip file names.

Each of these folders has either a .otf or .ttf (some have both) that I want out of them and moved to another folder.

I have tried a few methods of getting the full path of the files but every one of them leaves out the folder that the file is actually in.

Here is my latest try:

import os
import shutil
from pathlib import Path

result = []

for root, dirs, files in os.walk("."):
    for d in dirs:
       continue
    for f in files:
        if f.endswith(".otf"):
            print(f)
            p = Path(f).absolute()
            parent_dir = p.parents[1]
            p.rename(parent_dir / p.name)
        elif f.endswith(".ttf"):
            print(f)
            p = Path(f).absolute()
            parent_dir = p.parents[1]
            p.rename(parent_dir / p.name)      
        else:
            continue

Other attempts:

# parent_dir = Path(f).parents[1]
# shutil.move(f, parent_dir)

#print("OTF: " + f)
    #     fn = f
    #     f = f[:-4]
    #     f += '\\'
    #     f += fn
    #     result.append(os.path.realpath(f))

#os.path.relpath(os.path.join(root, f), "."))

I know this is something simple but I just can't figure it out. Thanks!


Solution

  • You should join the file name with the path name root:

    for root, dirs, files in os.walk("."):
        for d in dirs:
           continue
        for f in files:
            if f.endswith(".otf"):
                p = Path(os.path.join(root, f)).absolute()
                parent_dir = p.parents[1]
                p.rename(parent_dir / p.name)
            elif f.endswith(".ttf"):
                p = Path(os.path.join(root, f)).absolute()
                parent_dir = p.parents[1]
                p.rename(parent_dir / p.name)      
            else:
                continue