0

How could I take out the previous folder before the file from filepath using python? I mean I would like this:

C:\Projects\ProjectX\Stuff\File1\File1.jpg

to be

C:\Projects\ProjectX\Stuff\File1.jpg

Edit: And if the File is allready in "Stuff"-folder and not any subfolders after that, then I would like to leave the filepath like it was.

Zerom
  • 11
  • 2
  • Take off the file, take off the folder, add on the file: `os.path.join(dirname(dirname(filepath)), basename(filepath))`. See [**`os.path.basename`**](https://docs.python.org/3/library/os.path.html#os.path.basename) and [**`os.path.dirname`**](https://docs.python.org/3/library/os.path.html#os.path.dirname) – Peter Wood Feb 26 '18 at 12:30
  • Thank you, I got that working! – Zerom Feb 26 '18 at 12:55
  • But what about if I would like that code to check if there is that extra folder that needs to be deleted, and if the item is allready just in "Stuff" -folder, then leave the filepath like it was? Lets say our next file is C:\Projects\ProjectX\Stuff\File2.jpg and if I run the code, it will change to C:\Projects\ProjectX\File2.jpg. The "Stuff" -folder is what I want always retain. – Zerom Feb 26 '18 at 13:08
  • edit or create a new question or search for help – Peter Wood Feb 26 '18 at 13:09

2 Answers2

0

You can use shutil for transferring file from one place to another one

import shutil
shutil.move("C:\Projects\ProjectX\Stuff\File1\File1.jpg", "C:\Projects\ProjectX\Stuff\File1.jpg")

And you can simply follow answers from this post.

xyz
  • 326
  • 1
  • 12
0

You can try this also:-

from pathlib import PureWindowsPath
import os
path = "your path here till file"
file_name = path.split('\\')[-1]
p = PureWindowsPath(path)
new_extension = os.path.join(p.parents[1],file_name)
print(new_extension)
Narendra
  • 1,511
  • 1
  • 10
  • 20