Printing full path to all possible png files in directory - python

I need to display all png files in directory 'images'. The problem is there is subdirectory 'additional files' with one more png in it.
import glob
my_path = "images"
possible_files = os.path.join(my_path, "*.png")
for file in glob.glob(possible_files):
print(file)
How can i display full path to all png files in this directory including png files in subdirectories without new loop?

You can use os.walk method.
import glob
import os
for (dirpath, dirnames, filenames) in os.walk(YOURPATH):
possible_files = os.path.join(dirpath, "*.png")
for file in glob.glob(possible_files):
print(file)
'filenames' gives you the name of the files and you can use 'dirpath' to and 'dirnames' to determine which directory they are from, so you can even include some sub directories and skip others.

How about this? You are already using the os library.
my_path = "images"
out = [os.path.abspath(x) for x in glob.glob(my_path+"\\**\\*.png", recursive=True)]
out is a list with all png files with fullpath (with subdirectories)

Related

python unzip all files to parent directory

How can I extract all the .zip files in a certain directory to its parent directory?
I tried:
import zipfile
parent_directory = '../input'
directory = '../input/zip'
for f in os.listdir(directory):
with zipfile.ZipFile(os.path.join(directory,f), "r") as z:
z.extractall(parent_directory)
However the unzipped files are not saved in '..input/zip', they are saved in nested folders
This might be a bit exaggerated.
After files are unzipped, I run this to:
move the original .zip file up one directory level. (to avoid /src_filename' already exists error)
move all files from all subdirectories into the zip parent directory.
move the original .zip file back into the parent directory.
import os
import shutil
src = r'C:\Users\Owner\Desktop\PythonZip\PyUnzip01\child_dir\unzip_test2'
dest = r'C:\Users\Owner\Desktop\PythonZip\PyUnzip01\child_dir'
pdir = '../PyUnzip01'
os.replace(r"C:\Users\Owner\Desktop\PythonZip\PyUnzip01\child_dir\unzip_test2.zip", r"C:\Users\Owner\Desktop\PythonZip\PyUnzip01\unzip_test2.zip")
for root, subdirs, files in os.walk(src):
for file in files:
path = os.path.join(root, file)
shutil.move(path, dest)
os.replace(r"C:\Users\Owner\Desktop\PythonZip\PyUnzip01\unzip_test2.zip", r"C:\Users\Owner\Desktop\PythonZip\PyUnzip01\child_dir\unzip_test2.zip")

How to not include folders when zipping a file using ZipFile in python?

Is there a way to not generate folders during zip? When I extract the zip, it needs to show all the files directly without accessing a folder.
file_paths = utils.get_all_file_paths(path)
with ZipFile("{}/files.zip".format(path), "w") as zip:
for file in file_paths:
zip.write(file, os.path.basename(file))
I already tried arcname but it will still generate a folder which is files.
EDIT:
My code above will already remove the parent folder. Right now, when I extract the zip file, it will show a folder first with a name same as the zip name. What I want is to zip all the files and when I extract it, it will show all the files directly. Basically, no folders must show during extraction.
I hope following example will helpful to you
import os
import zipfile
TARGET_DIRECTORY = "../test"
ZIPFILE_NAME = "CompressedDir.zip"
def zip_dir(directory, zipname):
if os.path.exists(directory):
outZipFile = zipfile.ZipFile(zipname, 'w', zipfile.ZIP_DEFLATED)
for dirpath, dirnames, filenames in os.walk(directory):
for filename in filenames:
filepath = os.path.join(dirpath, filename)
outZipFile.write(filepath)
outZipFile.close()
if __name__ == '__main__':
zip_dir(TARGET_DIRECTORY, ZIPFILE_NAME)

Copy images in subfolders to another using Python

I have a folder with many subfolders that contains images. I want to copy these images of the subfolders to the destination folder. All images should be in one folder. With my current code, Python copies all subfolders to the destination folder, but thats not what I want. I only what the .jpg images. My current code is:
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for file in os.listdir(dir_src):
print(file)
src_file = os.path.join(dir_src, file)
dst_file = os.path.join(dir_dst, file)
shutil.copytree(src_file, dst_file)
I'm grateful for every tip
You can use os.walk:
import os
from shutil import copy
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for root, _, files in os.walk(dir_src):
for file in files:
if file.endswith('.jpg'):
copy(os.path.join(root, file), dir_dst)
or you can use glob if you're using Python 3.5+:
import glob
from shutil import copy
dir_src = r"/path/to/folder/with/subfolders"
dir_dst = r"/path/to/destination"
for file in glob.iglob('%s/**/*.jpg' % dir_src, recursive=True):
copy(file, dir_dst)

Folder containing subfolders, that contain multiple files (.xlsm, .pdf, .txt). How to rename .pdf files to subfolders' name?

This could be done with python, but I think I am missing a way to loop for all directories. Here is the code I am using:
import os
def renameInDir(directory):
for filename in os.listdir(directory):
if filename.endswith(".pdf"):
path = os.path.realpath(filename)
parents = path.split('/') //make an array of all the dirs in the path. 0 will be the original basefilename
newFilename=os.path.dirname(filename)+directory +parents[-1:][0] //reorganize data into format you want
os.rename(filename, newFilename)//rename the file
You should go with os.walk(). It will map the directory tree by the given directory param, and generate the file names.
Using os.walk() you'll accomplish the desired result is this way:
import os
from os.path import join
for dirpath, dirnames, filenames in os.walk('/path/to/directory'):
for name in filenames:
new_name = name[:-3] + 'new_file_extension'
os.rename(join(dirpath, name), join(dirpath, new_name))

How can I copy all files from all subfolders of a folder to another folder in Python? [duplicate]

I want to copy all my JPG files in one directory to a new directory.
How can I solve this in Python?I just start to learn Python.
Thanks for your reply.
Of course Python offers all the tools you need. To copy files, you can use shutil.copy(). To find all JPEG files in the source directory, you can use glob.iglob().
import glob
import shutil
import os
src_dir = "your/source/dir"
dst_dir = "your/destination/dir"
for jpgfile in glob.iglob(os.path.join(src_dir, "*.jpg")):
shutil.copy(jpgfile, dst_dir)
Note that this will overwrite all files with matching names in the destination directory.
import shutil
import os
for file in os.listdir(path):
if file.endswith(".jpg"):
src_dir = "your/source/dir"
dst_dir = "your/dest/dir"
shutil.move(src_dir,dst_dir)
Just use the following code
import shutil, os
files = ['file1.txt', 'file2.txt', 'file3.txt']
for f in files:
shutil.copy(f, 'dest_folder')
N.B.: You're in the current directory.
If You have a different directory, then add the path in the files list.
i.e:
files = ['/home/bucket/file1.txt', '/etc/bucket/file2.txt', '/var/bucket/file3.txt']
for jpgfile in glob.iglob(os.path.join(src_dir, "*", "*.jpg")):
shutil.copy(jpgfile, dst_dir)
You should write "**" before ".jpg" to search child directories. more "" means more subdirectory to search

Categories