The (later) plan for my project is this: iterate through my downloaded files, automatically create subfolders, sort my files by keywords and move them to subfolders matching the keywords. A prototype already worked. I don't understand, why this supposedly clean written sketch does not.
Every function works when called individually.
When I call them together the create_dir_by_keyword() function does not work, but does not give me an error message.
I suspect it does not work because I iterate through os.scandir(dir_keyword_files)
multiple times?
But why would it not work? Sorry, I am lost here.
import os
dir_source_files = 'source files'
dir_destination = 'destination'
dir_keyword_files = 'keywords'
scanned_dir_source_files = os.scandir(dir_source_files)
scanned_dir_keyword_files = os.scandir(dir_keyword_files)
scanned_dir_destination = os.scandir(dir_destination)
def scan_dir_source_files():
for file in scanned_dir_source_files:
print(file)
print("scan_dir_source_files() function called\n")
def scan_dir_keyword_files():
for file in scanned_dir_keyword_files:
print(file)
print("scan_dir_keyword_files() function called\n")
def read_keywords():
for file in scanned_dir_keyword_files:
keywords_in_file = open(file, 'r')
print(f"keyword found: {keywords_in_file.read()}")
print("read_keywords() function called\n")
def create_dir_by_keyword():
#reads the title of a scanned .txt and creates a subfolder with that title in dir_destination folder
for file in scanned_dir_keyword_files:
print((f"\nfile found in dir_keyword_files:\n{file} name of new folder: " + os.path.splitext(file.name)[0]))
new_dir_name = str(os.path.splitext(file.name)[0])
path_for_new_dir = os.path.join(dir_destination, new_dir_name)
try:
os.makedirs(path_for_new_dir, exist_ok = False)
print(f"directory creation succesful. created directory:\n{new_dir_name}")
except OSError as error:
print(f"directory creation not succesful. '{new_dir_name}' already exists")
print("create_dir_by_keyword() function called\n")
scan_dir_source_files()
scan_dir_source_files()
read_keywords()
create_dir_by_keyword()
Every function works by itself and individually, but if I call create_dir_by_keyword()
together with scan_dir_source_files()
and read_keywords()
no subfolder is created.
output:
<DirEntry 'How to Read People Like a Book -James W. Williams -Full Audiobook (192kbit_AAC).m4a'>
<DirEntry 'How to Talk to Anyone 92 Little Tricks for Big Success in Relationships Audiobook (128kbit_AAC).m4a'>
scan_dir_source_files() function called
scan_dir_source_files() function called
keyword found: 'audiobook', 'hörbuch', 'podcast'
read_keywords() function called
create_dir_by_keyword() function called
Tried to code this extra readable. Feedback on the readability of my code is welcome.