ackermanmoriii / python-fundamentals

0 stars 0 forks source link

Trt #32

Open ackermanmoriii opened 2 months ago

ackermanmoriii commented 2 months ago

import os from docx import Document

def extract_and_create_folders(directory):

Ensure the directory exists

if not os.path.exists(directory):
    print(f"The directory {directory} does not exist.")
    return

# Iterate over all files in the directory
for filename in os.listdir(directory):
    if filename.endswith(".docx"):
        filepath = os.path.join(directory, filename)
        doc = Document(filepath)

        # Extract the special content
        for para in doc.paragraphs:
            if "نام دانشجو:" in para.text:
                start = para.text.find("نام دانشجو:") + len("نام دانشجو:")
                end = para.text.find(".", start)
                if end != -1:
                    special_content = para.text[start:end].strip()

                    # Create a new folder named after the special content
                    new_folder_path = os.path.join(directory, special_content)
                    os.makedirs(new_folder_path, exist_ok=True)

                    # Save the special content in a text file within the new folder
                    with open(os.path.join(new_folder_path, "content.txt"), "w", encoding="utf-8") as f:
                        f.write(special_content)
                    break

Specify the directory containing the Word files

word_files_directory = "path_to_your_word_files_directory" extract_and_create_folders(word_files_directory)