Denise Rauschendorfer
10/13/2022
In this repository a function, "creating_folder_paths", is defined that creates folder paths on the user's mac/pc to match the folder paths used in another source code. This function may be useful if you are trying to run source code that contains files that are created, saved, and later called upon within the code. This function may also be useful in creating identical folder paths on multiple computers.
The following code was executed using Python 3.10.
In order to run the following code, the modules 're' and 'os' need to be imported.
import re
import os
To begin creating the function creating_folder_paths, any source code file needs to be converted into a .txt file.
Note: All of Sections 2-7 are contained within the 'def creating_folder_paths(source_file_name):'
To accomplish this, the following steps are taken:
- def is used to begin defining the function creating_folder_paths with the variable source_file_name.
- The filename titled "code_search.txt" is created to convert the source code into a .txt file.
- The source_code is then opened in read (r) mode.
- A for loop is created to iterate through each line in the source_code.
- Within this for loop, the code_search.txt (named filename) is opened in append (a) mode.
- A second for loop is created that iterates through each character within every line of the source_code.
- Within this nested for loop, an if/else statement is used to change any "\" character to "/" if necessary, and append the character to the code_search.txt file. This is necessary because "\", "\\", "/", and "//" are valid ways to delineate folders in other programming languages, but only "\\", "/", and "//" are valid in python.
- Once this process has repeated for all the characters in every line of source_code, the for loops are broken and the files are closed.
def creating_folder_paths(source_file_name):
filename = "code_search.txt"
source_code = open(source_file_name, "r")
for line in source_code.readlines():
with open(filename, 'a') as f:
for i in line:
if i == "\\":
i = "/"
f.write(i)
else:
f.write(i)
f.close()
source_code.close()
The .txt file, "code_search.txt", created in Section 2 is opened and each line of this file is checked to see if it contains a folder/file path located in the C drive. If a folder/file path is found, this character string is added to a list titled list.
To accomplish this, the following steps are taken:
- A list titled list is created.
- f/filename, the shorthand for code_search.txt, is opened in read (r) mode.
- A for loop is created to iterate through every line in f/filename.
- Within the for loop, a regular expression is used to search for any file path saved to the C drive.
- Nested within the for loop, an if statement is used to save any string of characters that matches the regular expression to list.
- Once this process has repeated for every line in f/filename, the for loop is broken and the file is closed.
list = []
f = open(filename, "r")
for line in f.readlines():
x = re.findall("\"C:.+\"", line)
if x != []:
list.append(x)
f.close()
The function input is used to verify that the user wants to create a folder path from each path found in the code_search.txt/source code. Every folder path that the user wants to create is then saved in a list titled list_keep.
To accomplish this, the following steps are taken:
- The question, possible_reply, and syntax_error text strings are created.
- A list titled list_keep is created.
- A for loop is created to iterate through each item in list. Recall that list was created in Section 3 and contains any string of characters from the .txt version of the source code that begins with ' "C:' and ends with ' " '.
- The input function is used to ask the user if they want to use item, a selected character string, to create a folder path.
- Within this for loop an if/elif/else statement is used. If the user selects "A" or "a" to indicate they want to use item to create a folder path, then item is added to list_keep. If the user selects "B" or "b" to indicate they do not want to use item to create a folder path, then the loop continues to the next item. Finally, if the user does not input a valid response ("A", "a", "B", or "b"), a syntax_error is printed in the console and the loop continues.
- Once this process has repeated for every item in list, the for loop is broken.
question = "Do you want to make a set of nested folders based on the string: "
possible_reply = "?\n A. Yes\n B. No\n"
syntax_error = "Syntax Error: You did not enter a valid response. Only 'A', 'a', 'B', or 'b' are valid responses."
list_keep = []
for item in list:
answer = input(question + str(item) + possible_reply)
if answer == "A" or answer == "a":
list_keep.append(item)
elif answer == "B" or answer == "b":
continue
else:
print(syntax_error)
Each file location in the list list_keep, created in Section 4, is divided into each separate folder. These folders are then saved in a list titled list1.
To accomplish this, the following steps are taken:
- A list titled list1 is created.
- A for loop is created to iterate through each item in the list list_keep that was created in Section 4.
- Within this for loop, each item is converted into a string titled str_item. A regular expression is then used to search through str_item and find every string of characters contained between, but not containing, two '/'. This list of character strings is then saved as x. For example, if str_item = ['"C:/folder1/folder2/folder3/file.txt"'], then x = ['/folder1/folder2/folder3/'].
- Each x is then converted into a string titled y and y is divided into separate strings wherever there is a '/'. This new list of character strings are then saved as z and appended to list1. For example, if y = ['/folder1/folder2/folder3/'], then z = ["['", 'folder', 'folder2', 'folder', "']"].
- Once this process has repeated for every item in list_keep, the for loop is broken.
list1 = []
for item in list_keep:
str_item = str(item)
x = re.findall("/.+/", str_item)
y = str(x)
z = re.split("/", y)
list1.append(z)
Any unwanted item in the list list1, created in Section 5, is removed. This includes: "['", "]'", and ' '. The simplified version of list1 is then saved as a list titled list2.
To accomplish this, the following steps are taken:
- A list titled list2 is created.
- A for loop is created to iterate through each i in the list list1 that was created in Section 5. Note: list1 contains a list of lists.
- Within this for loop, the first and last indices of i are removed. The first and last indices are "['" and "]'" and were created when y was converted into a string in Section 5.
- A new list titled list3 and a second for loop that iterates through each item, j, in each i list is created.
- Within this for loop, an if/else statement is used to remove any empty character strings (' ') from j and add every other value of j to list2. Note: any empty character strings (' ') is created whenever folder directories are distinguished using "//" or "\\" instead of "/" or "\".
- Once this process has repeated for every j in i and i in list1, the for loops are broken.
list2 = []
for i in list1:
i = i[1:-1]
list3 = []
for j in i:
if j == '':
continue
else:
list3.append(j)
list2.append(list3)
Next, the lists list_keep, created in Section 4, and list2, created in Section 6, are used to determine the parent directory of each folder that the user has specified they want to create. The function os.path.exists is used to determine if the folder already exists on the user's mac/pc. If the folder does not already exist, the function os.mkdir is used to create it.
To accomplish this, the following steps are taken:
- A for loop is created to iterate through each i in the list list_keep.
- Within the for loop, the index of each i in list_keep is saved as x.
- A second for loop is created to iterate through each j item in list2 that corresponds to the index of list_keep. Note: if list_keep[0] = ['"C:/folder1/folder2/folder3/file.txt"'], then list2[0] = ['folder1', 'folder2', 'folder3'].
- Within this second for loop, i is converted into a string y and the first 3 and last 3 indices of y are removed. These indices correspond to the characters ' ['" ' and ' "'] ' and are created when i is converted into a string.
- Next, a regular expression is used to split y into two strings. The first string contains every character before j, and the last string contains every character after j. This list is saved as z.
- z[0] is determined to be the parent directory of j and saved as parent_dir.
- The function os.path.join is used to specify the folder path that will be created by joining parent_dir and j.
- Next, the function os.path.exists is used to determine if the folder path already exists. This boolean answer is saved as is_exists.
- An if/else statement is then used. If is_exists is 'True', then the user is alerted of this in the console and the loop continues. If is_exists is 'False', then the function os.mkdir is used to create the folder path and the user is alerted of this in the console.
- Once this process has repeated for every j in list2[x] and i in list_keep, the for loops are broken.
for i in list_keep:
x = list_keep.index(i)
for j in list2[x]:
y = str(i)
y = y[3:-3]
z = re.split("" + j + ".+", y)
parent_dir = z[0]
path = os.path.join(parent_dir, j)
is_exist = os.path.exists(path)
if is_exist == True:
print("The folder path:" + str(path) + " exists")
continue
elif is_exist == False:
os.mkdir(path)
print("The folder path:" + str(path) + " was created")
Now that the function creating_folder_paths has been defined, it can be used by specifying the source_file_name of the source code. When defining the source_file_name, each folder should be delineated by either "/", "//", or "\\" for source_file_name to be a valid entry in python.
An example of how to use the function creating_folder_paths is shown below.
source_file_name = "C:\\folder1\\folder2\\folder3\\folder4\\example.py"
creating_folder_paths(source_file_name)
import re
import os
def creating_folder_paths(source_file_name):
filename = "code_search.txt"
source_code = open(source_file_name, "r")
for line in source_code.readlines():
with open(filename, 'a') as f:
for i in line:
if i == "\\":
i = "/"
f.write(i)
else:
f.write(i)
f.close()
source_code.close()
list = []
f = open(filename, "r")
for line in f.readlines():
x = re.findall("\"C:.+\"", line)
if x != []:
list.append(x)
f.close()
question = "Do you want to make a set of nested folders based on the string: "
possible_reply = "?\n A. Yes\n B. No\n"
syntax_error = "Syntax Error: You did not enter a valid response. Only 'A', 'a', 'B', or 'b' are valid responses."
list_keep = []
for item in list:
answer = input(question + str(item) + possible_reply)
if answer == "A" or answer == "a":
list_keep.append(item)
elif answer == "B" or answer == "b":
continue
else:
print(syntax_error)
list1 = []
for item in list_keep:
str_item = str(item)
x = re.findall("/.+/", str_item)
y = str(x)
z = re.split("/", y)
list1.append(z)
list2 = []
for i in list1:
i = i[1:-1]
list3 = []
for j in i:
if j == '':
continue
else:
list3.append(j)
list2.append(list3)
for i in list_keep:
x = list_keep.index(i)
for j in list2[x]:
y = str(i)
y = y[3:-3]
z = re.split("" + j + ".+", y)
parent_dir = z[0]
path = os.path.join(parent_dir, j)
is_exist = os.path.exists(path)
if is_exist == True:
print("The folder path:" + str(path) + " exists")
continue
elif is_exist == False:
os.mkdir(path)
print("The folder path:" + str(path) + " was created")
source_file_name = "C:\\folder1\\folder2\\folder3\\folder4\\example.py"
creating_folder_paths(source_file_name)