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
Related
I have a folder that contains a lot of subfolders, with images saved as png in each folder :
For example :
emotion\angry
emotion\disgusted
emotion\fearful
emotion\happy
I can remove the images in one of the folder using the below code :
folder_path = (r'C:\Users\emotion\angry')
test = os.listdir(folder_path)
for images in test:
if images.endswith(".png"):
os.remove(os.path.join(folder_path, images))
How do I create a loop to loop through each subfolder in emotion/?
As I do not want to manually write out all the code to clear all the folders...
You can list files using glob patterns and delete them using your normal os.remove.
import os
import glob
fileList = glob.glob('C:\Users\emotion\*\*.png')
for filePath in fileList:
try:
os.remove(filePath)
except:
print("Error while deleting file : ", filePath)
def all_dirs(directory):
# Returning list with all directories in selected directory
dir_list = []
for dir in [x[0] for x in os.walk(directory)]:
dir_list.append(dir)
return dir_list
This solution should work for every OS.
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 am new to python and currently work on data analysis.
I am trying to open multiple folders in a loop and read all files in folders.
Ex. working directory contains 10 folders needed to open and each folder contains 10 files.
My code for open each folder with .txt file;
file_open = glob.glob("home/....../folder1/*.txt")
I want to open folder 1 and read all files, then go to folder 2 and read all files... until folder 10 and read all files.
Can anyone help me how to write loop to open folder, included library needed to be used?
I have my background in R, for example, in R I could write loop to open folders and files use code below.
folder_open <- dir("......./main/")
for (n in 1 to length of (folder_open)){
file_open <-dir(paste0("......./main/",folder_open[n]))
for (k in 1 to length of (file_open){
file_open<-readLines(paste0("...../main/",folder_open[n],"/",file_open[k]))
//Finally I can read all folders and files.
}
}
This recursive method will scan all directories within a given directory and then print the names of the txt files. I kindly invite you to take it forward.
import os
def scan_folder(parent):
# iterate over all the files in directory 'parent'
for file_name in os.listdir(parent):
if file_name.endswith(".txt"):
# if it's a txt file, print its name (or do whatever you want)
print(file_name)
else:
current_path = "".join((parent, "/", file_name))
if os.path.isdir(current_path):
# if we're checking a sub-directory, recursively call this method
scan_folder(current_path)
scan_folder("/example/path") # Insert parent direcotry's path
Given the following folder/file tree:
C:.
├───folder1
│ file1.txt
│ file2.txt
│ file3.csv
│
└───folder2
file4.txt
file5.txt
file6.csv
The following code will recursively locate all .txt files in the tree:
import os
import fnmatch
for path,dirs,files in os.walk('.'):
for file in files:
if fnmatch.fnmatch(file,'*.txt'):
fullname = os.path.join(path,file)
print(fullname)
Output:
.\folder1\file1.txt
.\folder1\file2.txt
.\folder2\file4.txt
.\folder2\file5.txt
Your glob() pattern is almost correct. Try one of these:
file_open = glob.glob("home/....../*/*.txt")
file_open = glob.glob("home/....../folder*/*.txt")
The first one will examine all of the text files in any first-level subdirectory of home/......, whatever that is. The second will limit itself to subdirectories named like "folder1", "folder2", etc.
I don't speak R, but this might translate your code:
for filename in glob.glob("......../main/*/*.txt"):
with open(filename) as file_handle:
for line in file_handle:
# perform data on each line of text
I think nice way to do that would be to use os.walk. That will generate tree and you can then iterate through that tree.
import os
directory = './'
for d in os.walk(directory):
print(d)
This code will look for all directories inside a directory, printing out the names of all files found there:
#--------*---------*---------*---------*---------*---------*---------*---------*
# Desc: print filenames one level down from starting folder
#--------*---------*---------*---------*---------*---------*---------*---------*
import os, fnmatch, sys
def find_dirs(directory, pattern):
for item in os.listdir(directory):
if os.path.isdir(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
def find_files(directory, pattern):
for item in os.listdir(directory):
if os.path.isfile(os.path.join(directory, item)):
if fnmatch.fnmatch(item, pattern):
filename = os.path.join(directory, item)
yield filename
#--------*---------*---------*---------*---------*---------*---------*---------#
while True:# M A I N L I N E #
#--------*---------*---------*---------*---------*---------*---------*---------#
# # Set directory
os.chdir("C:\\Users\\Mike\\\Desktop")
for filedir in find_dirs('.', '*'):
print ('Got directory:', filedir)
for filename in find_files(filedir, '*'):
print (filename)
sys.exit() # END PROGRAM
pathlib is a good choose
from pathlib import Path
# or use: glob('**/*.txt')
for txt_path in [_ for _ in Path('demo/test_dir').rglob('*.txt') if _.is_file()]:
print(txt_path.absolute())
I have one million files in one folder, I want to copy just one hundred files from them in another folder:
import os
import shutil
dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")
for filename in os.listdir(dir_src):
shutil.copy( dir_src + filename, dir_dst)
print(filename)
This script copy for me all files, how to copy just 100000 files please?
Simply slice the list you want to iterate over:
for filename in os.listdir(dir_src)[:100]:
...
Indexing your list will allow you to perform actions on the nth (or i in this case) iteration.
import os
import shutil
dir_src = ("/Big_Folder")
dir_dst = ("/Small_Folder")
dirList = os.listdir(dir_src)
for i in range(len(dirList)):
if i == 100:
break
shutil.copy(dir_src + dirList[i], dir_dst)
print(filename)
I have files named "a1.txt", "a2.txt", "a3.txt", "a4.txt", "a5.txt" and so on. Then I have folders named "a1_1998", "a2_1999", "a3_2000", "a4_2001", "a5_2002" and so on.
I would like to make the conection between file "a1.txt" & folder "a1_1998" for example. (I'm guessing I'll need a regular expresion to do this). then use shutil to move file "a1.txt" into folder "a1_1998", file "a2.txt" into folder "a2_1999" etc....
I've started like this but I'm stuck because of my lack of understanding of regular expresions.
import re
##list files and folders
r = re.compile('^a(?P')
m = r.match('a')
m.group('id')
##
##Move files to folders
I modified the answer below slightly to use shutil to move the files, did the trick!!
import shutil
import os
import glob
files = glob.glob(r'C:\Wam\*.txt')
for file in files:
# this will remove the .txt extension and keep the "aN"
first_part = file[7:-4]
# find the matching directory
dir = glob.glob(r'C:\Wam\%s_*/' % first_part)[0]
shutil.move(file, dir)
You do not need regular expressions for this.
How about something like this:
import glob
files = glob.glob('*.txt')
for file in files:
# this will remove the .txt extension and keep the "aN"
first_part = file[:-4]
# find the matching directory
dir = glob.glob('%s_*/' % first_part)[0]
os.rename(file, os.path.join(dir, file))
A slight alternative, taking into account Inbar Rose's suggestion.
import os
import glob
files = glob.glob('*.txt')
dirs = glob.glob('*_*')
for file in files:
filename = os.path.splitext(file)[0]
matchdir = next(x for x in dirs if filename == x.rsplit('_')[0])
os.rename(file, os.path.join(matchdir, file))