How to get latest 3 .jpeg files from the folder - python

I want to get latest 3 ".jpeg" files from a folder using python
I tried like
import os
import glob
path = "path of the folder\\*.jpeg"
list_of_files = glob.iglob(path)
latest_file = max(list_of_files, key=os.path.getctime)
print(latest_file)
But I got only one file as output. How to get latest 3 files from a folder?

Just sort the list by date and pluck off the last three elements.
import os
import glob
path = "path of the folder\\*.jpeg"
latest_files = sorted(glob.iglob(path), key=os.path.getctime))
print(latest_files[-3:]

Try the following:
import os
import glob
files_path = os.path.join("C:\\Users\\User\\Pycharmprojects\\other\\", '*')
list_of_files = sorted(glob.iglob(files_path), key=os.path.getctime, reverse=True)
list_of_files=[i for i in list_of_files if i[-4:]=='jpeg']
latest_files = list_of_files[:3]
print(latest_files)

Related

Recursively unzipping a folder with ZipFile/Python

I am trying to write a script which can unzip something like this:
Great grandfather.zip
Grandfather.zip
Father.zip
Child.txt
What I have so far:
from os import listdir
import os
from zipfile import ZipFile, is_zipfile
#Current Directory
mypath = '.'
def extractor(path):
for file in listdir(path):
if(is_zipfile(file)):
print(file)
with ZipFile(file,'r') as zipObj:
path = os.path.splitext(file)[0]
zipObj.extractall(path)
extractor(path)
extractor(mypath)
I can unzip great grandfather and when I call the extractor again with grandfather as path. It doesn't go inside the if statement. Even though, I can list the contents of grandfather.
Replace extractor(path) by these two lines:
os.chdir(path)
extractor('.')
So your code becomes:
from os import listdir
import os
from zipfile import ZipFile, is_zipfile
#Current Directory
mypath = '.'
def extractor(path):
for file in listdir(path):
if(is_zipfile(file)):
print(file)
with ZipFile(file,'r') as zipObj:
path = os.path.splitext(file)[0]
zipObj.extractall(path)
os.chdir(path)
extractor('.')
extractor(mypath)

Copy pdfs in a directory to folders with the same name as the PDFs

I want to put the pdfs I have in a directory in to the folders with the same name. Those folders with the same name have already been created and are in the same directory as the pdf files I want to move in to them.
I am relatively new at python and have not gotten very far on the code. Currently when I run the below it only prints the .pdf files but does not print the subfolders within the directory (that is besides the point but I am not sure why I cant see the sub folders in the directory in the below code.)
import os
from shutil import copyfile
path_to_files = "C:\\tmp\\all_files_converted\\"
def copy_documents(file_path):
for f in os.listdir(file_path):
print(f)
copy_documents(path_to_files)
folders in directory C://tmp//all_files_converted//
pdf files with the same name as the folders in the same directory C://tmp//all_files_converted//
You can use pathlib and shutil to perform this:
from pathlib import Path
from shutil import move
path_to_files = Path(r"C:\tmp\all_files_converted")
for pdf_path in path_to_files.glob("*.pdf"):
dir_path = path_to_files / pdf_path.stem
dir_path.mkdir()
move(pdf_path, dir_path / pdf_path.name)
You can use shutil.move(src, dst)
import shutil
shutil.move(src, dst)
import os
from shutil import copyfile
from glob import glob
path_to_files = "pasta"
def copy_documents(path_to_files):
# os.path is a module to work with file paths
# Using the module glob to list all pdf files of a folder
for file_path in glob(os.path.join(path_to_files, "*.pdf")):
# basename will return the filename without the rest of the path ie: "something.pdf"
pdf_file_name = os.path.basename(file_path)
dest_folder = os.path.join(path_to_files, pdf_file_name[:-4])
print(f"Copy {file_path} to {dest_folder}")
copyfile(file_path, os.path.join(dest_folder, pdf_file_name))
copy_documents(path_to_files)
I recommend reading https://docs.python.org/3/library/os.path.html and https://docs.python.org/3/library/glob.html
for more info.

How to select and copy files with specific file names from one directory to another?

I have a directory with two different types of filenames daily/monthly:
report_20-10-2019.csv
report_21-10-2019.csv
report_22-10-2019.csv
report_09-2019.csv
report_10-2019.csv
report_11-2019.csv
I'm trying to copy only daily files to another directory. So far I'm able to copy all the files with the below code:
import shutil
import os
import glob
source_daily = '/path/to/files/to/copy/*.csv'
dest1 = 'path/to/directory/where/i/paste/my/files/'
files = os.listdir(source)
for file in glob.glob(source):
shutil.copy(file, dest1);
Would someone be able to help with this? Thanks in advance!
You can certainly do that,
import shutil
import os
import re
source = '/path/to/files/to/copy/'
dest1 = 'path/to/directory/where/i/paste/my/files/'
for filename in os.listdir(source):
filepath = os.path.join(source, filename)
if os.path.isfile(filepath):
if re.search(r"[0-9]+-[0-9]+-[0-9]+\.csv", filepath):
shutil.copy(filepath, dest1)
Hope it addresses your problem!
Using Regular Expressions should work for you:
import re
import shutil
import os
import glob
source_daily = '/path/to/files/to/copy/*.csv'
dest1 = 'path/to/directory/where/i/paste/my/files/'
files = os.listdir(source)
pattern = re.compile('\w+_[0-3]\d-[0-1]\d-\d{4}.csv') #naming-pattern
for file in glob.glob(source):
if pattern.match(file):
shutil.copy(file, dest1);

How to get the latest created file name and not the folder name using python?

The following code works well and gives me the require output with the file path.
import glob
import os
list_of_files = glob.glob('/path/to/folder/*')
latest_file = max(list_of_files, key=os.path.getctime)
print latest_file
But if the file is created then it will give the file path but if the folder is created then it will give the folder path. Whereas I was expecting only the file and not the folder created in a specific folder.
Kindly, suggest what I should do to get only the latest created file path and not the latest created folder path.
you can use something like this using lambdas
filelist = os.listdir(os.getcwd())
filelist = filter(lambda x: not os.path.isdir(x), filelist)
newest = max(filelist, key=lambda x: os.stat(x).st_mtime)
The complete answer is posted here
https://ubuntuforums.org/showthread.php?t=1526010
If you are importing os already, then you don't need any other modules to achieve this. os has a module called path which handles path related functions.
To check if a path is directory or a file, you can check os.path.isfile('/path/here') which will return a boolean true or false depending on if the passed parameter is a file or not
Try this:
import glob
import os
def check_file_status(path,direc=None):
if direc==None:
list_of_files = glob.glob(path)
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
else:
new_path = direc+'/*'
list_of_files = glob.glob(new_path)
latest_file = max(list_of_files, key=os.path.getctime)
return latest_file
if __name__ =="__main__":
path = '/your path to file/*'
if os.path.isfile(check_file_status(path)):
print(latest_file)
elif os.path.isdir(check_file_status(path)):
add_into_path = check_file_status(path)
print(check_file_status(path,add_into_path))

listing file names from the current directory that have png as extension

I am trying to list png image files from current folder I am working on but I get error.please help!
import os
def get_imlist(path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith(’.png’)]
You can use glob module for this -
Example -
>>> import glob
>>> glob.glob('*.png')
['this.png']
It will return you all files in current directory that end with .png extension as a list.
As #TigerhawkT3 spotted, your quotes need to be changed. Here are two possible approaches you can take which should return you the same results:
import os, glob
def get_imlist1(path):
return [os.path.join(path,f) for f in os.listdir(path) if f.endswith('.png')]
def get_imlist2(path):
return glob.glob(os.path.join(path, '*.png'))

Categories

Resources