3

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!

BSinGoogle
  • 33
  • 3

2 Answers2

2

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
blhsing
  • 91,368
  • 6
  • 71
  • 106
  • 1
    Thank you. It worked to move all the files to the parent directory. I'll have to try joining with root for my initial try where i wanted to move it to another directory. Thanks so much. I knew it had to be something simple i was missing. – BSinGoogle Oct 05 '18 at 16:08
0
 for root, dirs, files in os.walk(".")
     for d in dirs:
             continue
     for f in files:
             print(os.path.abspath(f))

You can use os.path.abspath() to get a path of a full file You would also need to still filter for the certain file types.

John Salzman
  • 500
  • 5
  • 14