ackermanmoriii / python-fundamentals

0 stars 0 forks source link

Hhhjj #36

Open ackermanmoriii opened 2 months ago

ackermanmoriii commented 2 months ago
from docx import Document
import os
import shutil

# Path to your Word file
word_file_path = 'path/to/your/file.docx'

# Load the Word document
doc = Document(word_file_path)

# Variable to store the extracted name
student_name = None

# Loop through each paragraph in the document
for para in doc.paragraphs:
    # Check if the paragraph starts with 'نام دانشجو:'
    if para.text.startswith('نام دانشجو:'):
        # Extract the student's name by removing the prefix and trailing dot
        student_name = para.text.replace('نام دانشجو:', '').strip().rstrip('.')
        break

# Check if a name was found
if student_name:
    print(f"Extracted Student Name: {student_name}")

    # Get the directory of the word file
    word_file_directory = os.path.dirname(word_file_path)

    # Create a new directory with the student's name
    new_folder_path = os.path.join(word_file_directory, student_name)

    try:
        os.makedirs(new_folder_path)
        print(f"Folder created at: {new_folder_path}")

        # Move the Word file to the new folder
        shutil.move(word_file_path, new_folder_path)
        print(f"Moved Word file to: {new_folder_path}")
    except FileExistsError:
        print(f"Folder '{new_folder_path}' already exists.")
    except Exception as e:
        print(f"An error occurred: {e}")

else:
    print("Student name not found in the document.")