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.
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.
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)
Related
I am trying to run a program with requires pVCF files alone as inputs. Due to the size of the data, I am unable to create a separate directory containing the particular files that I need.
The directory contains multiple files with 'vcf.gz.tbi' and 'vcf.gz' endings. Using the following code:
file_url = "file:///mnt/projects/samples/vcf_format/*.vcf.gz"
I tried to create a file path that only grabs the '.vcf.gz' files while excluding the '.vcf.gz.tbi' but I have been unsuccesful.
The code you have, as written, is just assigning your file path to the variable file_url. For something like this, glob is popular but isn't the only option:
import glob, os
file_url = "file:///mnt/projects/samples/vcf_format/"
os.chdir(file_url)
for file in glob.glob("*.vcf.gz"):
print(file)
Note that the file path doesn't contain the kind of file you want (in this case, a gzipped VCF), the glob for loop does that.
Check out this answer for more options.
It took some digging but it looks like you're trying to use the import_vcf function of Hail. To put the files in a list so that it can be passed as input:
import glob, os
file_url = "file:///mnt/projects/samples/vcf_format/"
def get_vcf_list(path):
vcf_list = []
os.chdir(path)
for file in glob.glob("*.vcf.gz"):
vcf_list.append(path + "/" + file)
return vcf_list
get_vcf_list(file_url)
# Now you pass 'get_vcf_list(file_url)' as your input instead of 'file_url'
mt = hl.import_vcf(get_vcf_list(file_url), force_bgz=True, reference_genome="GRCh38", array_elements_required=False)
I am trying to grab all of the mp3 files in my Downloads directory (after procedurally downloading them) and move them to a new file. However, anytime I try to use glob to grab a list of the available .mp3 files, I have to glob twice for it to work properly (the first time it is running it returns an empty list). Does anyone know what I am doing wrong here?
import glob
import os
import shutil
newpath = r'localpath/MP3s'
if not os.path.exists(newpath):
os.makedirs(newpath)
list_of_files = glob.glob('localpath/Downloads/*.mp3')
for i in list_of_files:
shutil.move(i, newpath)
This turned out to be a timing issue. The files I was trying to access were still in the process of downloading, with is why the glob was returning empty. I inserted a time.sleep(5) before the glob, and it is now running smoothly.
May I suggest an alternate approach
from pathlib import Path
from shutil import move
music = Path("./soundtrack")
# you can include absolute paths too...
newMusic = Path("./newsoundtrack")
# makes new folder specified in newMusic
newMusic.mkdir(exist_ok=True)
# will select all
list_of_files = music.glob("*")
# u want to select only mp3's do:
# list_of_files = music.glob("*.mp3")
for file in list_of_files:
move(str(file), str(newMusic))
i have this structure in my code.
app
src
script.py
data
data.ptk
i need to open the file "data.ptk" from "scrip.py", using os.path i'm able to extract the script path.
my_path = os.path.abspath(os.path.dirname(__file__))
But flowing the structure i need to go back 2 directories and then enter the "data" directory to open the file.
The easy way would be to decompose the string my_path with a split("/"), remove the last 2 words and add "data" ...
But I do not think it's the right way
The script.py need to be independent of the OS, that is the reason i'm not able to "hard code" the directory where de pkl file is placed
Any suggestions? thanks.
To elaborate on my comment more, you can see the documentation for pathlib here: https://docs.python.org/3/library/pathlib.html?highlight=pathlib#module-pathlib. It is a stock part of python3 (not sure about python2). I think the following would work:
from pathlib import Path
scriptPath = Path(__file__).absolute() # the absolute() is not strictly necessary
srcPath = scriptPath.parent
appPath = srcPath.parent
commonDirectory = appPath.parent # this could have been shortened with scriptPath.parent.parent.parent
dataPath = commonDirectory / 'data'
dtkFile = dataPath / 'data.ptk'
I'm kinda new to python and I feel like the answer to this is so simple but I have no idea what the answer is. I'm trying to move files from one place to another but I don't want to have to change my code every time I wanna move that file so I just want to get user input from the terminal.
import shutil
loop = True
while loop:
a = input()
shutil.move("/home/Path/a", "/home/Path/Pictures")
What do I have to put around the a so that it doesn't read it as part of the string?
This should do what you want. the os.path.join() will combine the string value in a, that you get from input with the first part of the path you have provided. You should use os.path.join() as this will form paths in a way that is system independent.
import shutil
import os
loop = True
while loop:
a = input()
shutil.move(os.path.join("/home/Path/", a), "/home/Path/Pictures")
Output:
>>> a = input()
test.txt
>>> path = os.path.join("/home/Path/", a)
>>> path
'/home/Path/test.txt'
You can also use "/home/Path/{0}".format(a) which will swap the value of a with {0}, or you can do do "/home/Path/{0}" + str(a) which will also do what you want.
Edited to account for Question in comment:
This will work if your directory doesn't have any sub-directories. it may still work if there are directories and files in there but I didn't test that.
import shutil
import os
files = os.listdir("/home/Path/")
for file in files:
shutil.move(os.path.join("/home/Path/", file), "/home/Path/Pictures")
one solution
a = 'test.csv'
path = '/home/Path/{}'.format(a)
>>> path
/home/Path/test.csv
Within in my script it's very rare that I run into this problem where I'm trying to move a file to this new folder that already happens to have a file with the same name, but it just happened. So my current code uses the shutil.move method but it errors out with the duplicate file names. I was hoping I could use a simple if statement of checking if source is already in destination and change the name slightly but can't get to that work either. I also read another post on here that used the distutils module for this issue but that one gives me an attribute error. Any other ideas people may have for this?
I added some sample code below. There is already a file called 'file.txt' in the 'C:\data\new' directory. The error given is Destination path already exist.
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
shutil.move(myfile, newpath)
You can just check that the file exists with os.path.exists and then remove it if it does.
import os
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
# if check existence of the new possible new path name.
check_existence = os.path.join(newpath, os.path.basename(myfile))
if os.path.exists(check_existence):
os.remove(check_existence)
shutil.move(myfile, newpath)
In Python 3.4 you can try the pathlib module. This is just an example so you can rewrite this to be more efficient/use variables:
import pathlib
import shutil
myfile = r"C:\data\file.txt"
newpath = r"C:\data\new"
p = pathlib.Path("C:\data\new")
if not p.exists():
shutil.move(myfile, newpath)
#Use an else: here to handle your edge case.