I'm trying to make a program which creates a new folder with different names inside a folder for every execution being made. I've pasted the code below I'm using:
import os
current_directory = os.getcwd()
name = "Day 1"
def folder_create(path, folder_name):
folder_names = [folder for folder in os.listdir(
path) if os.path.isdir(folder)]
if folder_name not in folder_names:
os.makedirs(folder_name)
else:
folder_num = folder_name.split(' ')[1]
new_folder_name = f'Day {int(folder_num) + 1}'
os.makedirs(new_folder_name, exist_ok=False)
folder_name = new_folder_name
return folder_name
if __name__ == '__main__':
name = folder_create(current_directory, name)
print(name)
This code only works twice meaning that it's only able to create two folders i.e, (Day 1 and Day 2) after executed two times but after then it gives FileExistError. Please help me find a way around as I just want it to create a new folder with every next day name i,e(Day 1, Day 2, Day 3) for each time executed.
This will work nicely. The real issue with your code was you kept supplying the same "name" argument to the folder_create() function.
All i've done is remove the need for supplying the name argument.
What it now does instead is to get the list of directories, sort the list, then get the last one using negative indexing. It then uses the last one create the new folder name. have fun
import os
current_directory = os.getcwd()
name = "Day 1"
def folder_create(path):
folder_names = [folder for folder in os.listdir(
path) if os.path.isdir(folder)]
folder_names.sort()
if "Day 1" not in folder_names:
os.makedirs('Day 1')
else:
folder_num = folder_names[-1].split(' ')[1]
new_folder_name = f'Day {int(folder_num) + 1}'
os.makedirs(new_folder_name, exist_ok=False)
folder_name = new_folder_name
return folder_name
if __name__ == '__main__':
name = folder_create(current_directory)
print(name)
This Solution Might Work For You-
import os
import random
current_directory = os.getcwd()
day_names = []
for i in range(0, 10+1): # 10 or Or Other Number+1 To Get Day Names That Number Of Times
day_names.append('Day '+str(i))
def folder_create(path, folder_name):
folder_names = [folder for folder in os.listdir(
path) if os.path.isdir(folder)]
if folder_name not in folder_names:
os.makedirs(folder_name)
else:
folder_num = folder_name.split(' ')[1]
new_folder_name = f'Day {int(folder_num) + random.randint(0, 10000)}' # To Get A Random Day Name If It Already Exixts
os.makedirs(new_folder_name, exist_ok=False)
folder_name = new_folder_name
return folder_name
if __name__ == '__main__':
for name in day_names: # Looping To Get Each Day Name
name = folder_create(current_directory, name)
print(name)
Related
I am not a programmer but I tried to automate renaming thousands of files using python. but this error appear. I've tried to shorten the path using win32api, using \\?\ notation before the path, even moving the folder to drive C:\ to shorten the path but the error still exist. I want the name of files to add 0 depending how many the files are. ex: if I have 2000 files, I want the name to be x0000,x0001, x0012, until the last x2000
import os, win32api
def main():
i = 0
path = "C:/New folder/"
path = win32api.GetShortPathName(path)
while i < len(os.listdir(path))+1:
filename = os.listdir(path)
s = len(str(i))
p = "x" + ("0" * (4-int(s))) + str(i) + ".jpg"
my_dest = p
my_source = path + str(filename)
my_dest =path + my_dest
os.rename(my_source, my_dest)
print(my_dest)
i+=1
if __name__ == '__main__':
main()
os.listdir(path) returns a list of filenames, not a single filename. You must iterate over this list:
import os, win32api
def main():
path = "C:/New folder/"
path = win32api.GetShortPathName(path)
filenames = os.listdir(path)
for i, filename in enumerate(filenames):
my_source = path + filename
new_name = 'x%04d.jpg' % i
my_dest = path + new_name
os.rename(my_source, my_dest)
print(my_source, my_dest) # print both
if __name__ == '__main__':
main()
On one of my local directories I print (without renaming):
C:/Booboo/ANGULA~1/.htaccess C:/Booboo/ANGULA~1/x0000.jpg
C:/Booboo/ANGULA~1/angucomplete-alt C:/Booboo/ANGULA~1/x0001.jpg
C:/Booboo/ANGULA~1/angular-route.min.js C:/Booboo/ANGULA~1/x0002.jpg
C:/Booboo/ANGULA~1/angular.html C:/Booboo/ANGULA~1/x0003.jpg
C:/Booboo/ANGULA~1/angular2.html C:/Booboo/ANGULA~1/x0004.jpg
C:/Booboo/ANGULA~1/angular3.html C:/Booboo/ANGULA~1/x0005.jpg
C:/Booboo/ANGULA~1/angular4.html C:/Booboo/ANGULA~1/x0006.jpg
C:/Booboo/ANGULA~1/angular5.html C:/Booboo/ANGULA~1/x0007.jpg
C:/Booboo/ANGULA~1/angular6.html C:/Booboo/ANGULA~1/x0008.jpg
C:/Booboo/ANGULA~1/authorization.py C:/Booboo/ANGULA~1/x0009.jpg
C:/Booboo/ANGULA~1/authorization.pyc C:/Booboo/ANGULA~1/x0010.jpg
etc.
I have a function that's returning a variable, and a second function that's using it. In my main func though flake8 is coming up that the variable is undefined.
I tried adding it as a global var, and placing a tox.ini file in the same folder as my script with ignore = F821 but this didn't register either. A
Any suggestions? Code block is below for reference. new_folder is the culprit
def createDestination(self):
'''
split the src variable for machine type
and create a folder with 'Evo' - machine
'''
s = src.split('\\')
new_folder = (dst + '\\Evo ' + s[-1])
if not os.path.exists(new_folder):
os.makedirs(new_folder)
return self.new_folder
def copyPrograms(new_folder):
'''
find all TB-Deco programs in second tier directory.
'''
# create file of folders in directory
folder_list = os.listdir(src)
# iterate the folder list
for folder in folder_list:
# create a new directory inside each folder
folder_src = (src + '\\' + folder)
# create a list of the files in the folder
file_list = os.listdir(folder_src)
# iterate the list of files
for file in file_list:
# if the file ends in .part .PART .dbp or .DBP - add it to a list
if (file.endswith('.part') or file.endswith('.PART') or
file.endswith('.dbp') or file.endswith('.DBP')):
# create a location variable for that file
file_src = (src + folder + '\\' + file)
# copy the file from the server to dst folder
new_file = ('Evo ' + file)
file_dst = (new_folder + '\\' + new_file)
if not os.path.exists(file_dst):
shutil.copy2(file_src, file_dst)
def main():
createDestination()
copyPrograms(new_folder)
if __name__ == "__main__":
main()
The first problem is that createDestination never defines an attribute self.new_folder, only a local variable new_folder. The indentation is also off, as you want to return new_folder whether or not you had to create it first.
def createDestination(self):
'''
split the src variable for machine type
and create a folder with 'Evo' - machine
'''
s = src.split('\\')
new_folder = (dst + '\\Evo ' + s[-1])
if not os.path.exists(new_folder):
os.makedirs(new_folder)
return new_folder # not self.new_folder
Second, you never assigned the return value of createDestination to any name so that you could pass it to copyPrograms as an argument.
def main():
new_folder = createDestination()
copyPrograms(new_folder)
Names have scope, and a variable named new_folder inside createDestination is distinct from one by the same name in main. As a corollary, there's no need to use the same name; the following definition of main works just as well:
def main():
d = createDestination()
copyPrograms(d)
and you don't even need to name the return value; you can pass it directly as
def main():
copyPrograms(createDestination())
I have a folder with some 1500 excel files . The format of each file is something like this:
0d20170101abcd.xlsx
1d20170101ef.xlsx
0d20170104g.xlsx
0d20170109hijkl.xlsx
1d20170109mno.xlsx
0d20170110pqr.xlsx
The first character of the file name is either '0' or '1' followed by 'd' followed by the date when the file was created followed by customer id(abcd,ef,g,hijkl,mno,pqr).The customer id has no fixed length and it can vary.
I want to create folders for each unique date(folder name should be date) and move the files with the same date into a single folder .
So for the above example , 4 folders (20170101,20170104,20170109,20170110) has to be created with files with same dates copied into their respective folders.
I want to know if there is any way to do this in python ? Sorry for not posting any sample code because I have no idea as to how to start.
Try this out:
import os
import re
root_path = 'test'
def main():
# Keep track of directories already created
created_dirs = []
# Go through all stuff in the directory
file_names = os.listdir(root_path)
for file_name in file_names:
process_file(file_name, created_dirs)
def process_file(file_name, created_dirs):
file_path = os.path.join(root_path, file_name)
# Check if it's not itself a directory - safe guard
if os.path.isfile(file_path):
file_date, user_id, file_ext = get_file_info(file_name)
# Check we could parse the infos of the file
if file_date is not None \
and user_id is not None \
and file_ext is not None:
# Make sure we haven't already created the directory
if file_date not in created_dirs:
create_dir(file_date)
created_dirs.append(file_date)
# Move the file and rename it
os.rename(
file_path,
os.path.join(root_path, file_date, '{}.{}'.format(user_id, file_ext)))
print file_date, user_id
def create_dir(dir_name):
dir_path = os.path.join(root_path, dir_name)
if not os.path.exists(dir_path) or not os.path.isdir(dir_path):
os.mkdir(dir_path)
def get_file_info(file_name):
match = re.search(r'[01]d(\d{8})([\w+-]+)\.(\w+)', file_name)
if match:
return match.group(1), match.group(2), match.group(3)
return None, None, None
if __name__ == '__main__':
main()
Note that depending on the names of your files, you might want to change (in the future) the regex I use, i.e. [01]d(\d{8})([\w+-]+) (you can play with it and see details about how to read it here)...
Check this code.
import os
files = list(x for x in os.listdir('.') if x.is_file())
for i in files:
d = i[2:10] #get data from filename
n = i[10:] #get new filename
if os.path.isdir(i[2:10]):
os.rename(os.getcwd()+i,os.getcwd()+d+"/"+i)
else:
os.mkdir(os.getcwd()+i)
os.rename(os.getcwd()+i,os.getcwd()+d+"/"+i)
Here's is the repl link
Try this out :
import os, shutil
filepath = "your_file_path"
files = list(x for x in os.listdir(filepath) if x.endswith(".xlsx"))
dates = list(set(x[2:10] for x in files))
for j in dates:
os.makedirs(filepath + j)
for i in files:
cid = i[10:]
for j in dates:
if j in i:
os.rename(filepath+i,cid)
shutil.copy2(filepath+cid, filepath+j)
I am trying to create a script in python 2.7 that will rename all the files in a directory. Below is the code I have so far. The first function removes any numbers in the file name. The second function is supposed to rename the new file name. I get the following error when the second function runs:
[Error 183] Cannot create a file when that file already exists
I know this is because I am not looping through the files and adding an incrementing number to the new filename, so the script changes the name of the first file, and then tries to change the name of the second file to the same name as the first, producing the error.
Can someone help me create a loop that adds an incrementing number to each filename in the directory?
I tried adding:
if file_name == filename:
file_name = file_name + 1
in the while loop, but that obviously doesn't work because I cant concatenate an integer with a string.
import os
def replace_num():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for file_name in file_list:
print("Old Name - " + file_name)
os.rename(file_name, file_name.translate(None, "0123456789"))
os.chdir(saved_path)
replace_num()
def rename_files():
file_list = os.listdir(r"C:\Users\Admin\Desktop\Python Pics")
print(file_list)
saved_path = os.getcwd()
print("Current Working Directory is " + saved_path)
os.chdir(r"C:\Users\Admin\Desktop\Python Pics")
for new_name in file_list:
print("New Name - " + new_name)
try:
os.rename(new_name, "iPhone")
except Exception, e:
print e
rename_files()
instead of doing:
if file_name == filename:
file_name = file_name + 1
do something like this:
counter = 0
for file_name in file_container:
if file_name == file_name: # this will always be True - so it's unnecessary
file_name = "{0}_{1}".format(file_name, counter)
counter += 1
I need to iterate over a folder tree. I have to check each subfolder, which looks like this:
moduleA-111-date
moduleA-112-date
moduleA-113-date
moduleB-111-date
moduleB-112-date
etc.
I figured out how to iterate over a folder tree. I can also use stat with mtime to get the date of the folder which seems easier than parsing the name of the date.
How do I single out modules with the same prefix (such as "moduleA") and compare their mtime's so I can delete the oldest?
Since you have no code, I assume that you're looking for design help. I'd lead my students to something like:
Make a list of the names
From each name, find the prefix, such as "moduleA. Put those in a set.
For each prefix in the set
Find all names with that prefix; put these in a temporary list
Sort this list.
For each file in this list *except* the last (newest)
delete the file
Does this get you moving?
I'm posting the code (answer) here, I suppose my question wasn't clear since I'm getting minus signs but anyway the solution wasn't as straight forward as I thought, I'm sure the code could use some fine tuning but it get's the job done.
#!/usr/bin/python
import os
import sys
import fnmatch
import glob
import re
import shutil
##########################################################################################################
#Remove the directory
def remove(path):
try:
shutil.rmtree(path)
print "Deleted : %s" % path
except OSError:
print OSError
print "Unable to remove folder: %s" % path
##########################################################################################################
#This function will look for the .sh files in a given path and returns them as a list.
def searchTreeForSh(path):
full_path = path+'*.sh'
listOfFolders = glob.glob(full_path)
return listOfFolders
##########################################################################################################
#Gets the full path to files containig .sh and returns a list of folder names (prefix) to be acted upon.
#listOfScripts is a list of full paths to .sh file
#dirname is the value that holds the root directory where listOfScripts is operating in
def getFolderNames(listOfScripts):
listOfFolders = []
folderNames = []
for foldername in listOfScripts:
listOfFolders.append(os.path.splitext(foldername)[0])
for folders in listOfFolders:
folder = folders.split('/')
foldersLen=len(folder)
folderNames.append(folder[foldersLen-1])
folderNames.sort()
return folderNames
##########################################################################################################
def minmax(items):
return max(items)
##########################################################################################################
#This function will check the latest entry in the tuple provided, and will then send "everything" to the remove function except that last entry
def sortBeforeDelete(statDir, t):
count = 0
tuple(statDir)
timeNotToDelete = minmax(statDir)
for ff in t:
if t[count][1] == timeNotToDelete:
count += 1
continue
else:
remove(t[count][0])
count += 1
##########################################################################################################
#A loop to run over the fullpath which is broken into items (see os.listdir above), elemenates the .sh and the .txt files, leaves only folder names, then matches it to one of the
#name in the "folders" variable
def coolFunction(folderNames, path):
localPath = os.listdir(path)
for folder in folderNames:
t = () # a tuple to act as sort of a dict, it will hold the folder name and it's equivalent st_mtime
statDir = [] # a list that will hold the st_mtime for all the folder names in subDirList
for item in localPath:
if os.path.isdir(path + item) == True:
if re.search(folder, item):
mtime = os.stat(path + '/' + item)
statDir.append(mtime.st_mtime)
t = t + ((path + item,mtime.st_mtime),)# the "," outside the perenthasis is how to make t be a list of lists and not set the elements one after theother.
if t == ():continue
sortBeforeDelete(statDir, t)
##########################################################################################################
def main(path):
dirs = os.listdir(path)
for component in dirs:
if os.path.isdir(component) == True:
newPath = path + '/' + component + '/'
listOfFolders= searchTreeForSh(newPath)
folderNames = getFolderNames(listOfFolders)
coolFunction(folderNames, newPath)
##########################################################################################################
if __name__ == "__main__":
main(sys.argv[1])