Saving the file downloaded with the pytube library to the desired location - python

For some reason I don't understand, the codes do not work, strangely, I do not get an error, it just does not save where I want, it saves to the folder where the file is run.
af = input("Link:")
yt = YouTube(af, on_progress_callback=progress_callback)
stream = yt.streams.get_highest_resolution()
print(f"Downloading video to '{stream.default_filename}'")
pbar = tqdm(total=stream.filesize, unit="bytes")
path = stream.download()
#Download path
b = open("\Download", "w")
b.write(stream.download())
b.close()
pbar.close()
print(Fore.LIGHTGREEN_EX+"Saved video to {}".format(path))
time.sleep(10)

First, to save the file in a specific directory we need to create the directory, I will do this through this function
import sys, os
def createDirectory(name):
path = sys.path[0] # Take the complete directory to the location where the code is, you can substitute it to the place where you want to save the video.
if not(os.path.isdir(f'{path}/{name}')): # Check if directory not exist
path = os.path.join(sys.path[0], name) # Set the directory to the specified path and the name that was given to it
os.mkdir(path) # Create a directory
After that we need to save the file in the newly created directory, for that within the "stream.download" in the parameter "output_path" we pass the total path to save and then the variable that contains the name of the newly created directory.
directoyName = 'Video'
createDirectory(directoyName)
path = sys.path[0] # Take the complete directory to the location where the code is, you can substitute it to the place where you want to save the video.
stream.download(output_path=f'{path}/{directoyName}') # Save the video in the newly created directory.
This way the file will be saved in the directory with the specified name.

Related

Opening PDF within a zip folder fitz.open()

I have a function that opens a zip file, finds a pdf with a given filename, then reads the first page of the pdf to get some specific text. My issue is that after I locate the correct file, I can't open it to read it. I have tried to use a relative path within the zip folder and a absolute path in my downloads folder and I keep getting the error:
no such file: 'Deliverables_Rev B\Plans_Rev B.pdf'
no such file: 'C:\Users\MyProfile\Downloads\Deliverables_Rev B\Plans_Rev B.pdf'
I have been commenting out the os.path.join line to change between the relative and absolute path as self.prefs['download_path'] returns my download folder.
I'm not sure what the issue with with the relative path is, any insight would be helpful, as I think it has to do with trying to read out of a zipped folder.
import zipfile as ZipFile
import fitz
def getjobcode(self, filename):
if '.zip' in filename:
with ZipFile(filename, 'r') as zipObj:
for document in zipObj.namelist():
if 'plans' in document.lower():
document = os.path.join(self.prefs['download_path'], document)
doc = fitz.open(document)
page1 = doc.load_page(0)
page1text = page1.get_text('text')
jobcode = page1text[page1text.index(
'PROJECT NUMBER'):page1text.index('PROJECT NUMBER') + 30][-12:]
return jobcode
I ended up extracting the zip folder into the downloads folder then parsing the pdf to get the data I needed. Afterwords I created a job folder where I wanted it and moved the extracted folder into it from the downloads folder.

Python - how to change directory

I am doing a school assignment where I have to take input from a user and save it to a text file.
My file structure will be something like:
- Customer register
- Customer ID
- .txt files 1-5
It can be saved in the python folder and I can make the folders like this:
os.makedirs("Customer register/Customer ID")
My question is, how do I set the path the text files are to be stored in, in the directory when I don't know the directory? So that no matter where the program is run it is saved in the "Customer ID" folder I create (but on the computer the program is run on)?
Also, how do I make this work on both windows and mac?
I also want to program to be able to be executed several times, and check if the folder is there and save to the "Customer ID" folder if it already exists. Is there a way to do that?
EDIT:
This is the code I am trying to use:
try:
dirs = os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
unique_filename = str(uuid.uuid4())
customerpath = os.getcwd()
os.chdir(customerpath + "/Folder/" + unique_filename)
I am able to create a folder and change the directory (everything in "try" works as I want).
When this folder is created I want to create a second folder with a random generated folder name (used for saving customer files). I can't get this to work in the same way.
Error:
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C:\Users\48736\PycharmProjects\tina/Folder/979b9026-b2f6-4526-a17a-3b53384f60c4'
EDIT 2:
try:
os.makedirs("Folder")
path = os.getcwd()
os.chdir(path + "/Folder")
print (os.getcwd())
except:
if os.path.exists:
path = os.getcwd()
os.chdir(os.path.join(path, 'Folder'))
print(os.getcwd())
def userId(folderid):
try:
if not os.path.exists(folderid):
os.makedirs(folderid)
except:
if os.path.exists(folderid):
os.chdir(path + "/Folder/" + folderid)
userId(str(uuid.uuid4()))
print(os.getcwd())
So I can now create a folder, change directory to the folder I have created and create a new folder with a unique filename within that folder.
But I can't change the directory again to the folder with the unique filename.
Any suggestions?
I have tried:
os.chdir(path + "/Folder/" + folderid)
os.chdir(path, 'Folder', folderid)
os.chdir(os.path.join(path, 'Folder', folderid))
But is still just stays in: C:\Users\47896\PycharmProjects\tina\Folder
You can use relative paths in your create directory command, i.e.
os.makedirs("./Customer register/Customer ID")
to create folder in project root (=where the primary caller is located) or
os.makedirs("../Customer register/Customer ID") in parent directory.
You can, of course, traverse the files tree as you need.
For specific options mentioned in your question, please, see makedirs documentation at Python 3 docs
here is solution
import os
import shutil
import uuid
path_on_system = os.getcwd() # directory where you want to save data
path = r'Folder' # your working directory
dir_path = os.path.join(path_on_system, path)
if not os.path.exists(dir_path):
os.makedirs(dir_path)
file_name = str(uuid.uuid4()) # file which you have created
if os.path.exists(file_name) and os.path.exists(dir_path):
shutil.move(file_name,os.path.join(dir_path,file_name))
else:
print(" {} does not exist".format(file_name))

Python's shutil Not copying Files to Specified Folder

I am trying to move files from one folder to another folder within the same directory buy am coming across a problem.
This is what my code looks like thus far:
current_dir = os.path.dirname(os.path.realpath(__file__))
folders = get_all_folders(current_dir)
os.mkdir('FINAL') # Final output stored here
for folder in folders:
img_list = list(os.listdir(current_dir))
for img in img_list:
img_path = os.path.join(current_dir, img)
final_folder = os.path.join(current_dir, 'FINAL')
shutil.copyfile(img_path, final_folder)
The FINAL folder is created as intended, however instad of copying the imgs over to that folder, a file called FINAL is created in each directory I am looping through.
Any ideas on how I can solve this?
I think the mistake you are doing here is that you are trying to find the images in the current directory instead of folders in the current directory. So, when you call shutil.copyfile(), you should ideally get a IsADirectoryError as per the code provided by you. Anyways, I guess this should work:
current_dir = os.path.dirname(os.path.realpath(__file__))
# Get all folder names in current directory before making the "FINAL" folder.
folders = get_all_folders(current_dir)
os.mkdir('FINAL') # Final output stored here
for folder in folders:
folder_path = os.path.join(current_dir, folder)
img_list = list(os.listdir(folder_path))
for img in img_list:
img_path = os.path.join(folder_path, img)
final_folder = os.path.join(current_dir, 'FINAL')
shutil.copyfile(img_path, final_folder)
Also, you need to remove the FINAL folder each time you run this script. Better make such checks in the code itself.

Specifying a partial path for os.path.join

I have a python script that creates a PDF and saves it in a subfoler of the folder where the script is saved. I have the following that saves the file to the subfolder:
outfilename = "Test" + ".pdf" #in real code there is a var that holds the name of the file
outfiledir = 'C:/Users/JohnDoe/Desktop/dev/PARENTFOLDER/SUBFOLDER/' #parent folder is where the script is - subfolder is where the PDFs get saved to
outfilepath = os.path.join(outfiledir, outfilename)
Is there a way I can save the PDFs to the subfolder without having to specify the full path? Lets say I wanted yto make this script an exe that multiple computers could use, how would I display the path so that the PDFs are just saved in the subfoler?
Thanks!
Try it:
import os
dir_name = os.path.dirname(os.path.abspath(__file__)) + '/subdir'
path = os.path.join(dir_name, 'filename')

How to export images into subdirectory in GIMP?

I use GIMP for some batch editing, part of this is exporting painting with the filename taken from original image "filename" with this code:
pdb.file_png_save_defaults(ima, drawable, fullpath, filename)
At this moment, I have
fullpath=filename
so it saves the image into same folder as the source and filename and fullpath are identical.
What I want to do is to put it into subdirectory in this folder, lets call it "subfolder". But if I try:
fullpath = '\subfolder\'+filename
I get an error, obviously, because I am working with Python (or any programming language) for like half an hour and I hardly know what I am doing. Does anybody know how to achieve exporting images into a subfolder?
UPDATE:
Now it looks like this
sourcename = pdb.gimp_image_get_filename(ima)
basedir = os.path.dirname(sourcename)
if os.path.isdir(os.path.join(basedir,'Subfolder')) is False:
os.makedirs(os.path.join(basedir,'Subfolder'))
fullpath = os.path.join(basedir,'Subfolder',filename)
... and it works well. Almost. Now I am facing the problem with diacritics in basedir. When basedir contains something like "C:\Ăšklid\" I get "no such file or directory" error when code is creating Subdirecotry in it. After I rename the source folder to "C:\Uklid\" it works with ease. But I do need it to work with every path valid in Windows OS. Can someone help me with that?
UPDATE 2:
Looks like unicode() did the trick:
sourcename = pdb.gimp_image_get_filename(ima)
basedir = os.path.dirname(sourcename)
if os.path.isdir(os.path.join(basedir,'Subfolder')) is False:
os.makedirs(unicode(os.path.join(basedir,'Subfolder')))
fullpath = os.path.join(basedir,'Subfolder',filename)
Try this out:
import os
sourcename = pdb.gimp_image_get_filename(ima) # gets full name of source file
basedir= os.path.dirname(sourcename) # gets path
name = pdb.gimp_layer_get_name(ima.layers[0]) # gets name of active layer
filename = name+'.png'
fullpath = os.path.join(basedir,'subfolder',filename) # use os.path.join to build paths
# new line vvv
os.makedirs(os.path.join(basedir,'subfolder')) # make directory if it doesn't exist
drawable = pdb.gimp_image_active_drawable(ima)
pdb.file_png_save_defaults(ima, drawable, fullpath, filename) # saves output file

Categories

Resources