I want to implement a python code which would select a 1 image after 3 images and so on till the last image in an sequential manner in the specified folder and copy those images to another folder.
Example : As shown in the screenshot
link : https://i.stack.imgur.com/DPdOd.png
The solution is same but I think it is more clear for all
import os
import shutil
path_to_your_files = 'your pics path'
copy_to_path = 'destination for your copy'
files_list = sorted(os.listdir(path_to_your_files))
orders = range(1, len(files_list) , 4)
for order in orders:
files = files_list[order] # getting 1 image after 3 images
shutil.copyfile(os.path.join(path_to_your_files, files), os.path.join(copy_to_path, files)) # copying images to destination folder
You can:
import os
files = os.listdir('YOUR PICS DIRECTORY HERE')
every_4th_files=[f for idx,f in zip(range(len(files)), files) if not idx%4]
Is it what you need?
Edit
To copy images I recommend to use shutil.copyfile.
If you encounter a problem - inform about it.
import os
from shutil import copyfile
files = sorted(os.listdir('Source Folder'))
4thFile = [fileName for index, file in zip(range(len(files)),files) if not index%4]
for file in 4thFile:
copyfile(os.path.join(src_path, f), os.path.join(dest_path, file))
That should get the job done.
Related
I plan to move the pictures in all subfolders (as shown in the picture) under the train file train/LUAD to another new folder train_new/LUAD. There are .jpg images in each subfolder such as the first one in the picture TCGA-05-4249-01Z-00-DX1.9fce0297-cc19-4c04-872c-4466ee4024db.
import os
import shutil
count = 0
def moveFiles(path, disdir):
dirlist = os.listdir(path)
for i in dirlist:
child = os.path.join('%s/%s' % (path, i))
if os.path.isfile(child):
imagename, jpg = os.path.splitext(i)
shutil.copy(child, os.path.join(disdir, imagename + ".jpg"))
continue
moveFiles(child, disdir)
if __name__ == '__main__':
rootimage = '/content/drive/MyDrive/stat841_final_data/train/LUAD'
disdir = '/content/drive/MyDrive/stat841_final_data/train_new/LUAD'
moveFiles(rootimage, disdir)
But it does not work. I only got image from the last subfolder except for other subfolders in my new folder train_new/LUAD...
Just to clarify, you want to move (not copy) images from a nested file structure to a new folder, without nesting?
Be aware that this could overwrite images, if multiple images share the same name!
import pathlib
def move_files(source_folder:pathlib.Path, target_folder:pathlib.Path):
target_folder.mkdir(parents=True, exist_ok=True)
for image_file in source_folder.rglob("*.jpg"): # recursively find image paths
image_file.rename(target_folder.joinpath(image_file.name))
If you are unsure maybe use the copy function first, so you won't lose your original data:
import pathlib
import shutil
def move_files(source_folder:pathlib.Path, target_folder:pathlib.Path):
target_folder.mkdir(parents=True, exist_ok=True)
for image_file in source_folder.rglob("*.jpg"): # recursively find image paths
shutil.copy(image_file, target_folder.joinpath(image_file.name))
I have more than 1000 JPG images in a folder having different name. I want to rename images as 0.JPG, 1.jpg, 2.jpg...
I tried different code but having below error:
The system cannot find the file specified: 'IMG_0102.JPG' -> '1.JPG'
The below code is one the codes found in this link: Rename files sequentially in python
import os
_src = "C:\\Users\\sazid\\Desktop\\snake"
_ext = ".JPG"
for i,filename in enumerate(os.listdir(_src)):
if filename.endswith(_ext):
os.rename(filename, str(i)+_ext)
How to solve this error. Any better code to rename image files in sequential order?
os.listdir only returns the filenames, it doesn't include the directory name. You'll need to include that when renaming. Try something like this:
import os
_src = "C:\\Users\\sazid\\Desktop\\snake"
_ext = ".JPG"
for i,filename in enumerate(os.listdir(_src)):
if filename.endswith(_ext):
src_file = os.path.join(_src, filename)
dst_file = os.path.join(_src, str(i)+_ext)
os.rename(src_file, dst_file)
just use glob and save yourself the headache
with glob your code turns into this:
import os
from glob import glob
target_dir = './some/dir/with/data'
for i, p in enumerate(glob(f'{target_dir}/*.jpg')):
os.rename(p, f'{target_dir}/{i}.jpg')
in this code glob() gives you a list of found file paths for files that have the .jpg extension, hence the *.jpg pattern for glob, here is more on glob
I have folders (river reach, eg W&S_River) which contain sub folders (one per gravel bar eg GravelBar_18) which contain images (50 - 300 per gravel bar). I'm trying to convert the images from jpg to tiff. I've got some code that does the conversion, but it takes some time and doesn't loop through the directory folder (river reach). I'm hoping to define the reach folder and have some code that opens each sub folder and converts each sub folder.
I've been trying to use os.walk based on what I've read here. I'm not getting any error messages, but it's not actually doing anything. Below is what I'm currently using to update the image in each sub folder.
import os
import os.path
from PIL import Image
import glob
os.chdir('E:/W&S_River/GravelBar_18')
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.save(file+".tiff", 'TIFF')
print("done")
for infile in glob.glob("/*/*.jpg"): # "/*" is important
...
#https://stackoverflow.com/a/36426997/11343720
#https://docs.python.org/3/library/glob.html#glob.glob
# ../../Tools/*/*.gif
import os
import os.path
from PIL import Image
import glob
def jpgToTIFF(folder):
os.chdir(folder)
for infile in glob.glob("*.jpg"):
file, ext = os.path.splitext(infile)
im = Image.open(infile)
im.save(file+".tiff", 'TIFF')
subfolders = [f.path for f in os.scandir('f:/work_rpi') if f.is_dir() ]
for foler in subfolders:
print(foler)
jpgToTIFF(folder)
https://stackoverflow.com/a/40347279/11343720
I have a folder of images, they have random names. What i want to do is change the images names to numbers for example 1.jpg 2.jpg 3.jpg and so on till the images are done.
what you need is os.listdir() to list all items in a folder and os.rename to rename those items.
import os
contents = os.listdir()
for i, filename in enumerate(contents):
os.rename(filename, i) # or i.jpg or whatever which is beyond that scope
import os
path = '/Path/To/Directory'
files = os.listdir(path)
i = 1
for file in files:
os.rename(os.path.join(path, file), os.path.join(path, str(i)+'.jpg'))
i = i+1
This can be done using os library:
If the folder has images only, no other files, you can run in the correct folder:
import os
count = 1
for picture in os.listdir():
os.rename(picture, f'{count}.jpg')
count += 1
You can read more about os here: https://docs.python.org/3/library/os.html
im trying to copy a .txt file from one dest to another. This code is running but the file isnt copying. What am i doing wrong?
import shutil
import os
src = "/c:/users/mick/temp"
src2 = "c:/users/mick"
dst = "/c:/users/mick/newfolder1/"
for files in src and src2:
if files.endswith(".txt"):
shutil.copy(files, dst)
Your for loop isn't actually searching through the files of each of your sources. In addition your for loop isn't looping through each of the sources but rather the letters in src and src2 that are present in both. This adjustment should handle what you need.
import os
src = ["c:/users/mick/temp", "c:/users/mick"]
dst = "c:/users/mick/newfolder1/"
for source in src:
for src_file in os.listdir(source):
if src_file.endswith(".txt"):
old_path = os.path.join(source, src_file)
new_path = os.path.join(dst, src_file)
os.rename(old_path, new_path)
You shouldn't need shutil for this situation as it is simply a more powerful os.rename that attempts to handle different scenarios a little better (to my knowledge). However if "newfolder1" isn't already existant than you will want to replace os.rename() with os.renames() as this attempts to create the directories inbetween.
shutils is useful for copying, but to move a file use
os.rename(oldpath, newpath)
I know the question is little older. But Here are the simple way to achieve your task. You may change the file extension as you wish. For copying you may use copy() & for moving yo may change it to move(). Hope this helps.
#To import the modules
import os
import shutil
#File path list atleast source & destination folders must be present not everything.
#*******************************WARNING**********************************************
#Make sure these folders names are already created while using the 'move() / copy()'*
#************************************************************************************
filePath1 = 'C:\\Users\\manimani\\Downloads' #Downloads folder
filePath2 = 'F:\\Projects\\Python\\Examples1' #Downloads folder
filePath3 = 'C:\\Users\\manimani\\python' #Python program files folder
filePath4 = 'F:\\Backup' #Backup folder
filePath5 = 'F:\\PDF_Downloads' #PDF files folder
filePath6 = 'C:\\Users\\manimani\\Videos' #Videos folder
filePath7 = 'F:\\WordFile_Downloads' #WordFiles folder
filePath8 = 'F:\\ExeFiles_Downloads' #ExeFiles folder
filePath9 = 'F:\\Image_Downloads' #JPEG_Files folder
#To change the directory from where the files to look // ***Source Directory***
os.chdir(filePath8)
#To get the list of files in the specific source directory
myFiles = os.listdir()
#To move all the '.docx' files to a different location // ***Destination Directory***
for filename in myFiles:
if filename.endswith('.docx'):
print('Moving the file : ' + filename)
shutil.move(filename, filePath4) #Destination directory name
print('All the files are moved as directed. Thanks')
import os, shutil
src1 = "c:/users/mick/temp/"
src2 = "c:/users/mick/"
dist = "c:/users/mick/newfolder"
if not os.path.isdir(dist) : os.mkdir(dist)
for src in [src1, src2] :
for f in os.listdir(src) :
if f.endswith(".txt") :
#print(src) # For testing purposes
shutil.copy(src, dist)
os.remove(src)
I think the error was that you were trying to copy a directory as a file, but you forgot to go through the files in the directory. You were just doing shutil.copy("c:/users/mick/temp/", c:/users/mick/newfolder/").