First, I see that the script imports `os` and `sys`, which suggests it's dealing with operating system-related tasks and handling command-line arguments or inputs. There are several functions defined:
`get_human_readable_size`: This function converts a file size in bytes to a human-readable format like KB, MB, GB, etc.
`check_empty_dirs`: This function walks through a given path and finds empty directories, returning a list of those directories.
`calculate_total_size`: This calculates the total size of a directory in bytes by walking through all its files and summing their sizes.
`check_orbit_subfolder`: This checks for the presence of an 'Orbit' subfolder within each immediate subfolder. It looks for nested 'Orbit' subfolders and ensures that there are `.csv` files inside the 'Orbit' directory.
`check_immediate_subfolder_files`: This checks for `.las` or `.laz` files within the immediate subfolders (not in any subdirectories).
`sanitize_path`: This removes surrounding quotes from the input path if present.
`check_folder`: This performs all the checks on the provided folder path according to the specified requirements. It includes counting files and folders, checking for empty directories, ensuring that the main folder doesn't contain an 'Orbit' subfolder, and verifying the presence of `.las`/`.laz` and `.csv` files in the appropriate subfolders.
`main`: This is the main function that handles user input and initiates the folder checks.
`if name == "main": main()`: This ensures that the `main()` function runs when the script is executed directly.
Now, let's consider the user's request:
Prompting for .laz/.las files: The script currently checks for `.las` or `.laz` files within the immediate subfolders. However, the user wants to ensure that all such files are present inside the first subfolders of the first main one, like `R1`, `R2`, etc.
Prompting for .csv files: Similarly, the `.csv` files should be present inside the 'Orbit' subfolders within these main subfolders (`R1`, `R2`, etc.).
Ensuring filenames include the name of the first subfolder: The user wants the `.las`/`.laz` and `.csv` filenames to contain the name of the first subfolder, such as `R1`, `R2`, etc.
Additionally, the user mentions looking for redundancies and optimization possibilities, suggesting they want to improve the script's efficiency or reduce unnecessary computations.
Let's think about how to implement these requirements:
Identifying First-Level Subfolders: We'll need to identify the first-level subfolders, likely named `R1`, `R2`, etc. This can be done by iterating through the immediate subdirectories of the main folder.
Checking for .las/.laz Files: For each first-level subfolder, we'll check if there are `.las` or `.laz` files present. Additionally, we'll verify that the filenames contain the subfolder's name.
Checking for .csv Files in 'Orbit' Subfolders: Within each `Orbit` subfolder located inside the first-level subfolders, we'll ensure that there are `.csv` files present. Moreover, these `.csv` files should also include the subfolder's name in their filenames.
Optimizing the Script:
Redundancies: Ensure that the script doesn't perform repetitive checks unnecessarily. For example, once an issue is found, it might be unnecessary to continue checking other subfolders unless specifically required.
Efficiency: Utilize more efficient methods for file and directory operations, possibly leveraging built-in modules or functions that are optimized for performance.
Code Structure: Refactor the code to enhance readability and maintainability. For instance, breaking down large functions into smaller, more manageable pieces.
User Input Handling: Improve the way user inputs are handled, providing clearer prompts and feedback to guide the user effectively.
Error Handling: Enhance error handling to manage unexpected scenarios gracefully, ensuring that the script doesn't crash unexpectedly and provides informative messages to the user.
Logging: Implement logging mechanisms to record the script's execution flow and any issues encountered, which can be helpful for debugging and auditing purposes.
Extensibility: Design the script in a modular way so that additional checks or requirements can be easily added in the future without significant refactoring.
By addressing these points, the script can become more robust, efficient, and user-friendly, aligning better with the user's specific needs and requirements.
Identify First-Level Subfolders:
Modify the script to iterate through the immediate subdirectories of the main folder, filtering for subfolders like `R1`, `R2`, etc.
Check for `.las` and `.laz` Files:
Within each first-level subfolder, search for files ending with `.las` or `.laz`.
Ensure that the filenames include the subfolder's name, e.g., `R1_file.las`.
Check for `.csv` Files in 'Orbit' Subfolders:
For each first-level subfolder, locate the corresponding 'Orbit' subfolder.
Within the 'Orbit' subfolder, search for `.csv` files.
Ensure that the `.csv` filenames include the subfolder's name, e.g., `R1_data.csv`.
Optimize the Script:
Redundancies: Once an issue is found (e.g., missing `.csv`), you can decide whether to continue checking other subfolders or exit early.
Efficiency: Use more efficient file traversal methods and avoid redundant computations.
Code Structure: Break down large functions into smaller, reusable functions to enhance readability.
Enhance User Input Handling:
Provide clear prompts guiding the user to enter valid folder paths.
Validate user inputs to prevent errors during execution.
Improve Error Handling:
Gracefully handle exceptions related to file access permissions, non-existent directories, etc.
Inform the user of any issues encountered without crashing the script.
Implement Logging:
Add logging to record the script's execution flow and any issues found.
This aids in debugging and provides a history of actions taken.
Ensure Filenames Contain Subfolder Names:
When searching for files, include a condition to check if the filename contains the subfolder's name.
If not, flag it as an issue.
By implementing these enhancements, your script will become more efficient, user-friendly, and aligned with your specific requirements for managing `.las`, `.laz`, and `.csv` files within designated subfolders.
Assistant
To update and enhance your Python script according to your outlined requirements, here are detailed steps and suggestions on how to implement and optimize it effectively:
Identify First-Level Subfolders:
Modify the script to iterate over the immediate subdirectories within the main directory. Specifically, look for subfolders that match the naming pattern (e.g., R1, R2, etc.).
Check for .las and .laz Files:
For each identified first-level subfolder, verify the presence of .las or .laz files.
Ensure that each file includes the respective subfolder's name in the filename. For instance, a file in R1 should be named something like R1_file.las.
Check for .csv Files in 'Orbit' Subfolders:
Navigate to the 'Orbit' subfolder within each first-level subfolder.
Verify the presence of .csv files, ensuring their names also include the parent subfolder's name, e.g., R1_data.csv.
Optimize the Script:
Reduce Redundancies: Avoid running the same checks multiple times for the same directories unless necessary. Use flags or conditions to skip redundant operations if an issue is already detected.
Efficiency Improvements: Consider using efficient directory traversal methods, like os.walk() or Pathlib, to streamline directory and file operations.
Refactor Code: Simplify functions and ensure they have a single responsibility. This will enhance readability and make debugging easier.
Enhance User Input Handling:
Provide concise and clear prompts that guide the user in specifying valid folder paths or parameters.
Implement input validation to catch invalid paths or problematic user inputs before processing.
Improve Error Handling:
Use exception handling (try-except blocks) to manage potential errors like missing directories, permission issues, or unexpected file structures gracefully.
Provide the user with informative error messages to clarify what went wrong, instead of allowing the script to crash.
User
'''
import os
import sys
def get_human_readable_size(size, decimal_places=2):
"""
Converts a file size in bytes to a human-readable format.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0 or unit == 'TB':
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size(path):
"""
Calculates the total size of the given directory in bytes.
"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
# Skip if it's a symbolic link
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size
def check_orbit_subfolder(subfolder_path):
"""
Checks the 'Orbit' subfolder within a given immediate subfolder.
Returns True if any issues are found, else False.
"""
issues = False
orbit_folder = os.path.join(subfolder_path, "Orbit")
print(f"\n🔍 Checking 'Orbit' subfolder in: {subfolder_path}")
code
if not os.path.exists(orbit_folder):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True # Issue found
# Check for nested 'Orbit' subfolders
for root, dirs, files in os.walk(orbit_folder):
if 'orbit' in [d.lower() for d in dirs]:
nested_orbit_path = os.path.join(root, 'Orbit')
print(f"❌ Nested 'Orbit' subfolder found at: {nested_orbit_path}")
issues = True
break # No need to check further if nested Orbit is found
# Prevent walking into nested 'Orbit' subfolders
for root, dirs, files in os.walk(orbit_folder):
dirs[:] = [d for d in dirs if d.lower() != 'orbit']
csv_present = any(file.lower().endswith('.csv') for file in files)
if not csv_present:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_folder}")
issues = True
break # No need to check further if .csv is missing
return issues
Assistant
To adapt your script to ensure that all .las/.laz files are present in the first-level subfolders and that all .csv files are within their respective 'Orbit' subfolders, while also verifying that filenames include the parent subfolder name, here are the required changes and optimizations:
Key Changes and Enhancements:
Identify Subfolder Patterns (e.g., R1, R2, ...):
Adjust identification logic to determine what constitutes a valid first-level subfolder, typically starting with a pattern like R1, R2, etc.
Check File Presence and Naming:
Ensure .las/.laz files exist within each main subfolder and contain the subfolder's name.
Verify .csv files exist inside 'Orbit' subfolders and include the subfolder's name.
Optimize the Script:
Consider making functions more concise and focusing on reusability.
Reduce nested loops where possible to enhance readability and efficiency.
Enhance Messaging and Output:
Improve feedback to the user, clarifying what is being checked and issues encountered.
Below is an optimized and updated version of relevant portions of your script:
python
User
error:
Traceback (most recent call last):
File "C:\Users\SPL\Documents\Scriptz\check_las_orbit_0.02.py", line 96, in
main()
File "C:\Users\SPL\Documents\Scriptz\check_las_orbit_0.02.py", line 87, in main
sanitized_path = sanitize_path(folder_path)
^^^^^^^^^^^^^
NameError: name 'sanitize_path' is not defined. Did you mean: 'sanitized_path'?
Assistant
The NameError you're encountering indicates that the function sanitize_path is not defined in the provided script at the point where it's being called. This error prompts you to check the definition and import the sanitize_path function into your script correctly.
Here’s how you can resolve the issue:
Define the sanitize_path Function:
Ensure that the sanitize_path function is defined in your script. Since this function wasn't included in the code snippet provided with the error, let's quickly define it:
python
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
Placement in the Script:
You should place this function somewhere before its first call in the script, typically alongside other utility functions. Ensure it's well-documented for clarity and future reference.
Check for Typographical Errors:
Ensure the function name is consistently used. Typographical errors like a missing letter or incorrect capitalization might cause naming issues that lead to a NameError.
Verify Imports and Context:
Since sanitize_path is a standalone utility function, no imports are required apart from reproducing its usage in this script's context. Make sure the function is used after its definition in your main script.
Here's how you can integrate it into your main script:
python
User
give the complete script revised
Assistant
Below is the revised version of your script with all the discussed changes applied. The script now ensures that .las/.laz files are present in the first-level subfolders and that .csv files are within their respective 'Orbit' subfolders, containing the parent subfolder's name in their filenames:
python
User
it should messaging me that all the .las/.laz files are present and also the .csv. and if somet of them are missing it should tell me where these are missing
Assistant
To address your requirements, I'll modify the script to provide explicit messages about whether all .las/.laz files and .csv files are present in their respective locations. It will also specify if any files are missing and where these issues occur.
Here's the updated script:
python
User
the total size of the directory should be in bytes, and even the number of files present
Assistant
To adjust your script so that it reports the total size of the directory in bytes and lists the total number of files within the directory, here’s the updated version of your script:
python
User
print distinction number of .laz/.las and number of .csv
Assistant
To further refine the script and display the distinct count of .las/.laz and .csv files within their respective locations, we can update the script to include counting these specific files separately. Here's the updated version of your script:
python
User
Total number of files: 11 i guess this is identifing the main folder as a file. excluded it if it is possible. i need printed out just what's inside that main
Assistant
It seems like the script is counting the total number of files, including those at the root level of the main folder itself. To ensure you're only counting files inside the subfolders of the main directory (excluding files directly in the main folder), you can adjust the counting logic as follows:
I'll update the script so that it only counts files that are inside the subfolders, not those directly in the main directory itself:
python
User
do icons can be printed out in powershell 7?
Assistant
Yes, PowerShell 7 supports the printing of icons and other Unicode characters, including emoji, thanks to improvements in Unicode support. This means you can print special characters, emoji, and icons directly in the PowerShell console if your terminal and font settings support Unicode characters.
Here's an example of printing some icons and emoji in PowerShell 7:
powershell
Write-Host "Here are some icons and emoji:"
Write-Host "✅ Success"
Write-Host "⚠️ Warning"
Write-Host "❌ Error"
Write-Host "📂 Folder"
Write-Host "👋 Goodbye"
Considerations:
Font Support: Ensure that your PowerShell terminal uses a font that supports a wide range of Unicode characters. Fonts like Consolas or Cascadia Code are often recommended for this purpose.
Encoding: PowerShell 7 already uses UTF-8 by default, which supports a vast range of Unicode characters, so you shouldn't have to worry about encoding issues.
Terminal Settings: Some terminal emulators might not display all emoji or icons properly due to their own limitations. If you experience issues, try different terminal emulators such as Windows Terminal or a PowerShell Integrated Scripting Environment (ISE).
By ensuring your PowerShell environment is configured properly, you can enjoy rich text outputs with icons and emoji to enhance readability and user experience in your scripts.
User
can you integrated them in my script? to make it prettier
Assistant
Certainly! Integrating icons and emojis in your script can improve readability and make it more user-friendly. Here’s the updated version of your Python script with added icons and emojis for a better visual appeal:
python
User
Now, something different. another script that, based on a .txt file create a set of folders on my desktop
it should search for the name of a municipality usually in the first line of this .txt example: LOG LAS NIKAIA 24-04-2024. it shoul take the municipality name in this example: NIKAIA to create the main folder. then the date to create a sub folder. and Asking me how many more days are there to add from that day, to create another set of subfolders goin up in crescent date, i guess.
Assistant
To create a script that reads a .txt file to create a set of folders based on the name of a municipality and a date, I'll go through the necessary steps and logic. The script will:
Extract the municipality name and date from the first line of the .txt file.
Create a main folder named after the municipality on your desktop.
Create a subfolder for the given date and additional subfolders for subsequent days.
Prompt you to specify how many additional days you want to add.
Here's a Python script to accomplish this task:
python
import os
from datetime import datetime, timedelta
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
municipality = parts[-3] # Assuming the municipality is always the third last element
date_str = parts[-1] # Assuming the date is the last element
return municipality, date_str
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
for i in range(num_days + 1): # Include the start date and additional days
current_date_obj = start_date_obj + timedelta(days=i)
current_date_str = current_date_obj.strftime("%d-%m-%Y")
subfolder_path = os.path.join(main_folder_path, current_date_str)
os.makedirs(subfolder_path, exist_ok=True)
print(f"📂 Created subfolder: {subfolder_path}")
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file: ").strip()
if not os.path.isfile(file_path):
print("❗ The specified path is not a valid file.")
return
municipality, date = extract_info_from_file(file_path)
print(f"Municipality: {municipality}, Date: {date}")
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
User
inside the main one, will create this folders too: GEO, ZIP, TRAJ, TXT, DXF, LAS
Inside the GEO other subfolders which should correspond to foolders created based the dates created before.
E.G. LOG LAS NIKAIA 24-04-2024: NIKAIA is the municipality, 24-04-2024 is the date. it should prompt me how many more days there are usually consecutive to the one find in the csv. then those folder name should also be the folder name of the subfolders inside GEO.
Assistant
To satisfy your requirements, we'll extend the script to do the following:
Main Folder: Create a main folder named after the municipality.
Subfolders within the Main Folder: Create subfolders named GEO, ZIP, TRAJ, TXT, DXF, LAS.
Date-Based Subfolders: Create date-based subfolders inside the main folder, as well as inside the GEO folder.
User Input for Additional Days: Prompt the user to specify how many additional consecutive days to create folders for.
Here's an updated version of the script:
python
User
it should be asking me also the path of the .txt. it should accepts path inside the quotations marks ("path")
Assistant
We can enhance the script to accept paths enclosed in quotation marks and strip those quotes as part of parsing. This lets users provide paths in a more natural way when they're copying from other sources.
Here’s how you can modify the script:
python
User
Enter the path to the .txt file (in quotes if needed): "F:\BCKPCK\patrasso\PATRASSO_LAS_030924.txt"
Traceback (most recent call last):
File "C:\Users\SPL\Documents\Scriptz\folder_creation.0.0.1.py", line 91, in
main()
File "C:\Users\SPL\Documents\Scriptz\folder_creation.0.0.1.py", line 79, in main
municipality, date = extract_info_from_file(sanitized_path)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\SPL\Documents\Scriptz\folder_creation.0.0.1.py", line 20, in extract_info_from_file
municipality = parts[-3] # Assuming the municipality is always the third last element
~~~~~^^^^
IndexError: list index out of range
Ok. this is the erro. you specify "is always the third element" it is not always like that. the municipality name could be the first also. let's enhanced the logic: usually the words that could interfere are "log" and "las" if those are not present then the municipality name could be the second or the first, for example.
Assistant
To enhance the script and reliably extract the municipality name irrespective of its position in the line, we'll need to refine our parsing logic. We'll consider excluding known keywords such as "LOG" and "LAS" to identify the municipality name. This flexibility should accommodate varying formats in your input text.
Here's how you can adjust your script to handle these scenarios:
python
User
another error:
Assistant
Let's diagnose and resolve the issue causing the error. The previous script might have encountered problems due to parsing assumptions. Let's ensure the script is robust and doesn't assume specific positions for the municipality or other data unless it's clear. Please share the specific error message, but based on common issues, here's a refined version of the script:
python
User
the logic error
Enter the path to the .txt file (in quotes if needed): "F:\BCKPCK\patrasso\PATRASSO_LAS_030924.txt"
❗ Error reading file: Could not determine municipality or date
the first lines of the txt could be even composed like this:
PATRASSO 03 09 2024
so, the municipality name it is not necessary in the first line. i tell you this to better the logic with some more context
Assistant
Thank you for providing more context. Let's refine the logic to handle cases where the municipality and date might not be adjacent or in a straightforward position within the line. We'll make the script more flexible and resilient by:
Checking for Date Formats: We'll scan parts of the line for something that resembles a date.
Identifying the Municipality: We'll default to assuming other non-keyword parts of the line are potential municipality names, but filtered to ensure typical date patterns don't get confused as such.
Here's how we can adjust the script:
python
User
PS C:\Users\SPL\Documents\Scriptz> python .\folder_creation.0.0.1.py
Enter the path to the .txt file (in quotes if needed): "F:\BCKPCK\patrasso\PATRASSO_LAS_030924.txt"
❗ Error reading file: Could not determine date.
this error. maybe due to logic mistakes, as you can see in the filename there's 030924.
Inside you could read this:
PATRASSO 03 09 2024
03 09 2024: is how the date is structered differently from 03-09-2024. but it could happen to be find inside the txt or outside, in the file name.
you can seen in the file name eve the name of the municipality: PATRASSO
Assistant
Got it! To handle the variability in date and municipality extraction, let's improve the script to:
Search Both the File Name and Content: Extract dates and municipality from the file name if they're not clear from the content.
Flexible Date Parsing: Adjust the logic to handle dates without delimiters found inside the file content (e.g., 03 09 2024).
Here's how you can adjust the script to manage these scenarios:
python
User
MMM, IT DOESNT WORK. SAME ERROR: ❗ Error reading file: Could not determine date.
LET'S CLARIFY THIS AGAIN:
THIS IS THE TXT FILENAME "PATRASSO_LAS_030924.TXT"
INSIDE THERE'S THIS:
PATRASSO 03 09 2024
Assistant
Thanks for clarifying. Let's simplify and correct the logic to properly extract both the municipality name and date from the file name and the file content, considering the structure you've provided. We'll check both the file's content and the filename to ensure we capture both values accurately.
Here's the updated script:
python
User
❗ Error reading file: File content is not in the expected format.
DUNNO WHAT DOES THAT MEAN THE FILE HAS AN EXTENSION OF .TXT
Assistant
The error message "File content is not in the expected format" indicates that the script attempted to parse the content of your .txt file but didn't find the data structured as expected in the script logic. Let's address this by making the script more flexible and providing better diagnostic output.
Here’s an updated script that provides more information and handles different cases:
python
User
now it works. let's talk about the date i have used the one from the example (03 09 2024) it correctly created that one and asked me how many after that, so it created the 04-09-2024 and 05-09-2024 subfolders.
If i wanted to skip, for example the 06-09-204, cause i'm only needing the 07-09-2024, how could the logic and the prompting could be enhanced? maybe asking a different question in the prompt? you tell me.
Assistant
To give you control over which specific additional dates to create, we can enhance the script to prompt the user for specific dates instead of asking for a simple count of consecutive days. Here's a plan for how we can modify the script:
Prompt for Specific Dates: Instead of asking for a number of additional days, prompt the user to input specific dates they wish to add.
Input Validation: Validate that the input dates are correctly formatted.
Add Specified Dates Only: Create subfolders for these specified dates.
Let's implement this change in the logic:
python
User
now very different after changing ssd on a macbook air how do i reinstall the macos ? what are some of that proprietary difficoulties that apple imposes? in opening the chassis and reinstalling the os?
Assistant
Reinstalling macOS after replacing the SSD on a MacBook Air can be a straightforward process, but it does involve several steps, both hardware and software-related. Here’s a guide to help you through the process, along with some common difficulties you might face.
Hardware Considerations:
Opening the Chassis:
Tools Needed: You'll need a set of specialized tools, typically including a Pentalobe screwdriver (P5) for the outer screws, and a Torx (T5 or T6, depending on the model) for the internal components.
Proprietary Fasteners: Apple uses proprietary screws which require specific screwdrivers.
Delicate Internal Components: Be cautious of the fragile connectors and components inside. Carefully disconnect the battery before proceeding with any part replacement to prevent accidental damage.
Void Warranty: Keep in mind that opening your MacBook might void your warranty or AppleCare coverage if applicable, especially if unauthorized service is detected.
Software Considerations:
Reinstallation of macOS:
Internet Recovery Mode: Newer MacBooks can use Internet Recovery to reinstall macOS. This feature allows you to download the version of macOS that originally shipped with your Mac (or the closest available version still hosted by Apple) directly from the Internet.
Accessing: Start your Mac and immediately press and hold Command + Option + R until you see the spinning globe. This mode requires an internet connection.
Bootable USB Installer: If Internet Recovery isn't suitable due to network requirements or version considerations, you can create a bootable USB installer on another Mac running macOS.
Creating a USB Installer: Download macOS from the App Store or Apple’s website, to a USB drive (at least 16GB), and use the createinstallmedia command:
Installation: Boot from the USB by holding Option at startup and select the installer.
Proprietary Difficulties & Considerations:
User
Sorry for changing the topic. now back to the script. all the folders are created correctly, the new prompt let me insert dates how i wanted them. but with the subfolders RUN i have a problem.
to create the subfolders run inside the date folders (in MAIN and inside GEO) maybe a prompt should be a solution. asking me how many R folders (renamed R1, R2, R3 etc etc.) for each date entered in the prompt before.
maybe that's a solution
Assistant
Certainly! We can enhance the script to prompt the user for the number of "R" folders (like R1, R2, etc.) for each date folder. This approach allows you to specify how many of these subfolders you'd like to create within each date folder in both the main folder and the GEO subfolder. Here's how you can implement this:
python
User
Enter the number of 'R' subfolders to create for each date (e.g., 3 for R1, R2, R3):
ok this is good but, if i want a different numbers of folders for each date?
also, can the prompt to input dates be semplified? very rarely i could create a folder outside the year and the month after the first date. so if for example the first date folder is 030924, hardly the date would be with next month for example 031024 or the next year 030925. so prompting just the days inside that month or year could be quickier.
Assistant
To address these requirements:
Different Numbers of 'R' Folders for Each Date:
We can prompt you to specify the number of 'R' folders individually for each date. This will allow you to customize the folder structure according to your needs.
Simplified Date Input:
We'll enhance the date input process so you can quickly enter just the days within the same month or year. This means you can specify days directly, and the script will construct the full date using the month and year from the initial date.
Use Python's logging module to capture details about the script's execution and any issues encountered during the checks.
This can help both during development and when auditing the script's behavior in production environments.
Ensure Filenames Contain Subfolder Names:
When verifying file names, add a condition that checks if the filename includes the subfolder's identifier.
If not, flag these instances for user review or correction.
Sample Code Outline:
Here's a simplified structure to visualize these recommendations:
python
import os
import logging
def setup_logging():
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def find_first_level_subfolders(main_path):
# Identify the first-level directories
subfolders = [d for d in os.listdir(main_path) if os.path.isdir(os.path.join(main_path, d))]
return subfolders
def check_files(subfolder):
# Check .las/.laz files in the given subfolder
for root, _, files in os.walk(subfolder):
for file in files:
if file.endswith(('.las', '.laz')):
if subfolder in file:
logging.info(f'Found valid file: {file}')
else:
logging.warning(f'File {file} does not include subfolder name.')
def check_csv_files_in_orbit(subfolder):
orbit_path = os.path.join(subfolder, 'Orbit')
if os.path.exists(orbit_path):
for file in os.listdir(orbit_path):
if file.endswith('.csv'):
if subfolder in file:
logging.info(f'Found valid CSV: {file}')
else:
logging.warning(f'CSV {file} does not include subfolder name.')
def main():
setup_logging()
main_folder = input("Enter the path to the main folder: ").strip()
subfolders = find_first_level_subfolders(main_folder)
for subfolder in subfolders:
subfolder_path = os.path.join(main_folder, subfolder)
check_files(subfolder_path)
check_csv_files_in_orbit(subfolder_path)
if __name__ == "__main__":
main()
This outline incorporates your main requirements and sets the foundation for further refinement and enhancement based on specific needs or additional functionality.
def check_immediate_subfolder_files(subfolder_path):
"""
Checks for .las or .laz files within the immediate subfolder (not in any subdirectories).
Returns True if any issues are found, else False.
"""
issues = False
# List all files in the immediate subfolder (not in subdirectories)
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
return True
code
las_laz_files = [f for f in files if f.lower().endswith(('.las', '.laz'))]
if not las_laz_files:
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
return issues
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def check_folder(folder_path):
"""
Performs all the checks on the provided folder path according to the specified requirements.
"""
issues_found = False # Flag to track if any issues are found
code
# Check if the folder exists and is a directory
if not os.path.exists(folder_path):
print(f"❌ Folder '{folder_path}' does not exist.")
return
if not os.path.isdir(folder_path):
print(f"❌ The path '{folder_path}' is not a directory.")
return
print(f"\n✅ Checking folder: {folder_path}")
# Calculate total size
total_size = calculate_total_size(folder_path)
# Initialize counters
total_files = 0
total_folders = 0 # Includes subfolders and their subfolders
# Enumerate all subfolders and count files/folders
for root, dirs, files in os.walk(folder_path):
# Exclude the main folder itself from folders count
if root != folder_path:
total_folders += len(dirs)
total_files += len(files)
# Display the counts and size
print("\n📊 **Folder Statistics**")
print(f" - Total files: {total_files}")
print(f" - Total folders/subfolders: {total_folders}")
print(f" - Total size: {get_human_readable_size(total_size)} ({total_size} bytes)")
# Check for empty folders
empty_directories = check_empty_dirs(folder_path)
if empty_directories:
issues_found = True
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
# Check that the main folder does NOT contain an "Orbit" subfolder
orbit_in_main = os.path.join(folder_path, "Orbit")
if os.path.exists(orbit_in_main):
issues_found = True
print(f"\n❌ The main folder '{folder_path}' **should not** contain an 'Orbit' subfolder.")
# Now, iterate through all immediate subfolders to check for required files and 'Orbit' subfolders
print("\n🔄 **Checking Immediate Subfolders**")
with os.scandir(folder_path) as entries:
for entry in entries:
if entry.is_dir():
subfolder_path = entry.path
# Skip any subfolder named 'Orbit' as the main folder should not have it
if entry.name.lower() == 'orbit':
continue
print(f"\n📂 Checking subfolder: {subfolder_path}")
# Check for `.las`/`.laz` files in the immediate subfolder
las_laz_issue = check_immediate_subfolder_files(subfolder_path)
if las_laz_issue:
issues_found = True
# Check for 'Orbit' subfolder and `.csv` files within it
orbit_issue = check_orbit_subfolder(subfolder_path)
if orbit_issue:
issues_found = True
# Final comprehensive summary
print("\n📋 **Final Report**")
print(f" - Total files: {total_files}")
print(f" - Total folders/subfolders: {total_folders}")
print(f" - Total size: {get_human_readable_size(total_size)} ({total_size} bytes)")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All checks passed. No issues found.**")
def main():
"""
Main function to handle user input and initiate folder checks.
"""
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
# Sanitize the path to remove surrounding quotes if present
sanitized_path = sanitize_path(folder_path)
check_folder(sanitized_path)
if name == "main":
main()
'''
My script. I want to prompt it out that the all .laz/.las files are present inside the first subfolders of the first main one (which usually are E.G. R1, R2, R3, R4, R5, R6, R7, R8 etc. etc.). and that all .csv are present inside the second subfolders which is 'Orbit' inside of E.G. R1, R2, R3, R4, R5, R6, R7, R8 etc. etc.. To make it more advanced the las/laz name and the csv should contioin in their names the name of the first subfolder E.G. R1, R2, R3, R4, R5, R6, R7, R8, ETC. ETC.
IF YOU SEE REDUNDANCIES AND OPTIMIZATION POSSIBLE TELL ME ABOUT IT and will explore these ones later.
import os
import sys
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
"""
issues_found = False
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues = check_las_laz_files(subfolder_path, subfolder_name)
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues = check_csv_files_in_orbit(subfolder_path, subfolder_name)
if orbit_issues:
issues_found = True
return issues_found
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
"""
issues = False
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
for file in files:
if file.lower().endswith(('.las', '.laz')):
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
return issues
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
"""
issues = False
orbit_path = os.path.join(subfolder_path, "Orbit")
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
for file in files:
if file.lower().endswith('.csv'):
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
return issues
def main():
issues_found = False
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found = check_files_in_first_subfolders(sanitized_path)
if issues_found:
print("\n⚠️ **Some issues were found during the check.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Areas of Redundancy and Optimization:
Refactoring for Clarity: Functions have been streamlined to reduce complexity and redundancy, especially in directory and file checks.
String Matching: Ensure subfolder name matching is case-insensitive using .lower().
Error Handling: Proper error messaging for file access issues.
User Interaction: Improved input prompts and feedback for better guidance and understanding.
By following this structure, the script will now more efficiently verify the presence and naming of files, streamlining the process and improving user experience.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
# Define other functions (e.g., check_files_in_first_subfolders, check_las_laz_files, etc.)
def main():
issues_found = False
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found = check_files_in_first_subfolders(sanitized_path)
if issues_found:
print("\n⚠️ **Some issues were found during the check.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
By defining and properly placing this function, the script should execute without encountering a NameError. Make sure that all function names match their definitions, and that all relevant functions are implemented and placed correctly in your script.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def get_human_readable_size(size, decimal_places=2):
"""
Converts a file size in bytes to a human-readable format.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0 or unit == 'TB':
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size(path):
"""
Calculates the total size of the given directory in bytes.
"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
"""
issues = False
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
for file in files:
if file.lower().endswith(('.las', '.laz')):
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
if not any(file.lower().endswith(('.las', '.laz')) for file in files):
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
return issues
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
"""
issues = False
orbit_path = os.path.join(subfolder_path, "Orbit")
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
csv_present = False
for file in files:
if file.lower().endswith('.csv'):
csv_present = True
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
if not csv_present:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_path}")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
return issues
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
"""
issues_found = False
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues = check_las_laz_files(subfolder_path, subfolder_name)
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues = check_csv_files_in_orbit(subfolder_path, subfolder_name)
if orbit_issues:
issues_found = True
return issues_found
def main():
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found = check_files_in_first_subfolders(sanitized_path)
total_size = calculate_total_size(sanitized_path)
print(f"\nTotal size of directory: {get_human_readable_size(total_size)}")
empty_directories = check_empty_dirs(sanitized_path)
if empty_directories:
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Key Modifications:
Functionality for .las/.laz and .csv Files: The script checks if the filenames contain the parent subfolder's name and ensures presence in the correct directories.
Error Handling: Improved permission handling and messaging.
Modular Code: Functions have been tailored for specific checks, aiding clarity and maintainability.
This complete script should meet the requirements of ensuring proper file locations and naming conventions according to your specifications.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def get_human_readable_size(size, decimal_places=2):
"""
Converts a file size in bytes to a human-readable format.
"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024.0 or unit == 'TB':
break
size /= 1024.0
return f"{size:.{decimal_places}f} {unit}"
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size(path):
"""
Calculates the total size of the given directory in bytes.
"""
total_size = 0
for dirpath, dirnames, filenames in os.walk(path):
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
"""
files = []
issues = False
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
las_laz_files = [f for f in files if f.lower().endswith(('.las', '.laz'))]
if not las_laz_files:
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
for file in las_laz_files:
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
if not issues:
print(f"✅ All `.las`/`.laz` files are present and correctly named in: {subfolder_path}")
return issues
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
"""
orbit_path = os.path.join(subfolder_path, "Orbit")
issues = False
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True
files = []
csv_files = []
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
csv_files = [f for f in files if f.lower().endswith('.csv')]
for file in csv_files:
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
if not csv_files:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_path}")
issues = True
if not issues:
print(f"✅ All `.csv` files are present and correctly named in: {orbit_path}")
return issues
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
"""
issues_found = False
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues = check_las_laz_files(subfolder_path, subfolder_name)
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues = check_csv_files_in_orbit(subfolder_path, subfolder_name)
if orbit_issues:
issues_found = True
return issues_found
def main():
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found = check_files_in_first_subfolders(sanitized_path)
total_size = calculate_total_size(sanitized_path)
print(f"\nTotal size of directory: {get_human_readable_size(total_size)}")
empty_directories = check_empty_dirs(sanitized_path)
if empty_directories:
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Key Features:
Detailed Feedback: The script now prints clear messages about the presence of .las/.laz and .csv files, specifying issues if files are missing or incorrectly named.
File Naming Verification: Ensures that the filenames contain their parent subfolder's name, emphasizing the correct organization structure.
Efficiency: The code structure provides transparency on checks conducted, easily allowing future extensions or modifications.
This structured feedback should help in easily identifying missing files and ensuring correct directory compositions.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size_and_files(path):
"""
Calculates the total size of the given directory in bytes and counts the total number of files.
"""
total_size = 0
total_files = 0
for dirpath, dirnames, filenames in os.walk(path):
total_files += len(filenames)
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size, total_files
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
"""
files = []
issues = False
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
las_laz_files = [f for f in files if f.lower().endswith(('.las', '.laz'))]
if not las_laz_files:
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
for file in las_laz_files:
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
if not issues:
print(f"✅ All `.las`/`.laz` files are present and correctly named in: {subfolder_path}")
return issues
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
"""
orbit_path = os.path.join(subfolder_path, "Orbit")
issues = False
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True
files = []
csv_files = []
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
csv_files = [f for f in files if f.lower().endswith('.csv')]
for file in csv_files:
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
if not csv_files:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_path}")
issues = True
if not issues:
print(f"✅ All `.csv` files are present and correctly named in: {orbit_path}")
return issues
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
"""
issues_found = False
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues = check_las_laz_files(subfolder_path, subfolder_name)
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues = check_csv_files_in_orbit(subfolder_path, subfolder_name)
if orbit_issues:
issues_found = True
return issues_found
def main():
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found = check_files_in_first_subfolders(sanitized_path)
total_size, total_files = calculate_total_size_and_files(sanitized_path)
print(f"\nTotal size of directory: {total_size} bytes")
print(f"Total number of files: {total_files}")
empty_directories = check_empty_dirs(sanitized_path)
if empty_directories:
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Key Changes:
Total Size and File Count: The calculate_total_size_and_files function computes both the total size of the directory in bytes and the total number of files, which are then displayed.
Feedback: The script now explicitly reports if all files are present and correctly named, or if any are missing along with specific locations.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size_and_files(path):
"""
Calculates the total size of the given directory in bytes and counts the total number of files.
"""
total_size = 0
total_files = 0
for dirpath, dirnames, filenames in os.walk(path):
total_files += len(filenames)
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size, total_files
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
Returns: issues, las_laz_count
"""
files = []
issues = False
las_laz_count = 0
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
las_laz_files = [f for f in files if f.lower().endswith(('.las', '.laz'))]
las_laz_count = len(las_laz_files)
if not las_laz_files:
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
for file in las_laz_files:
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
if not issues:
print(f"✅ All `.las`/`.laz` files are present and correctly named in: {subfolder_path} ({las_laz_count} files)")
return issues, las_laz_count
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
Returns: issues, csv_count
"""
orbit_path = os.path.join(subfolder_path, "Orbit")
issues = False
csv_count = 0
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True, csv_count
files = []
csv_files = []
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
csv_files = [f for f in files if f.lower().endswith('.csv')]
csv_count = len(csv_files)
for file in csv_files:
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
if not csv_files:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_path}")
issues = True
if not issues:
print(f"✅ All `.csv` files are present and correctly named in: {orbit_path} ({csv_count} files)")
return issues, csv_count
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
Returns the total distinct count of `.las`/`.laz` and `.csv` files.
"""
issues_found = False
total_las_laz_files = 0
total_csv_files = 0
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues, las_laz_count = check_las_laz_files(subfolder_path, subfolder_name)
total_las_laz_files += las_laz_count
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues, csv_count = check_csv_files_in_orbit(subfolder_path, subfolder_name)
total_csv_files += csv_count
if orbit_issues:
issues_found = True
return issues_found, total_las_laz_files, total_csv_files
def main():
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found, total_las_laz_files, total_csv_files = check_files_in_first_subfolders(sanitized_path)
total_size, total_files = calculate_total_size_and_files(sanitized_path)
print(f"\nTotal size of directory: {total_size} bytes")
print(f"Total number of files: {total_files}")
print(f"Total number of .las/.laz files: {total_las_laz_files}")
print(f"Total number of .csv files: {total_csv_files}")
empty_directories = check_empty_dirs(sanitized_path)
if empty_directories:
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Key Enhancements:
File Counts: The script now tracks the total number of .las/.laz and .csv files across all subfolders and specifically within their expected locations, printing these totals.
Explicit Feedback: Provides clear feedback on file presence and naming correctness, making it easier to spot what is correct and what needs fixing.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size_and_files(path):
"""
Calculates the total size of the given directory in bytes and counts the total number of files within subdirectories.
"""
total_size = 0
total_files = 0
for dirpath, dirnames, filenames in os.walk(path):
if dirpath != path: # Skip counting files in the main directory itself
total_files += len(filenames)
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size, total_files
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
Returns: issues, las_laz_count
"""
files = []
issues = False
las_laz_count = 0
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
las_laz_files = [f for f in files if f.lower().endswith(('.las', '.laz'))]
las_laz_count = len(las_laz_files)
if not las_laz_files:
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
for file in las_laz_files:
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
if not issues:
print(f"✅ All `.las`/`.laz` files are present and correctly named in: {subfolder_path} ({las_laz_count} files)")
return issues, las_laz_count
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
Returns: issues, csv_count
"""
orbit_path = os.path.join(subfolder_path, "Orbit")
issues = False
csv_count = 0
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True, csv_count
files = []
csv_files = []
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
csv_files = [f for f in files if f.lower().endswith('.csv')]
csv_count = len(csv_files)
for file in csv_files:
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
if not csv_files:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_path}")
issues = True
if not issues:
print(f"✅ All `.csv` files are present and correctly named in: {orbit_path} ({csv_count} files)")
return issues, csv_count
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
Returns the total distinct count of `.las`/`.laz` and `.csv` files.
"""
issues_found = False
total_las_laz_files = 0
total_csv_files = 0
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues, las_laz_count = check_las_laz_files(subfolder_path, subfolder_name)
total_las_laz_files += las_laz_count
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues, csv_count = check_csv_files_in_orbit(subfolder_path, subfolder_name)
total_csv_files += csv_count
if orbit_issues:
issues_found = True
return issues_found, total_las_laz_files, total_csv_files
def main():
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found, total_las_laz_files, total_csv_files = check_files_in_first_subfolders(sanitized_path)
total_size, total_files = calculate_total_size_and_files(sanitized_path)
print(f"\nTotal size of directory (excluding main): {total_size} bytes")
print(f"Total number of files (excluding main): {total_files}")
print(f"Total number of .las/.laz files: {total_las_laz_files}")
print(f"Total number of .csv files: {total_csv_files}")
empty_directories = check_empty_dirs(sanitized_path)
if empty_directories:
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Key Adjustment:
The calculate_total_size_and_files function now only counts files inside subdirectories, excluding those directly in the main directory. This is achieved by checking if dirpath != path to skip files at the root level. This provides a more accurate count of the files nested within subfolders.
import os
import sys
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def check_empty_dirs(path):
"""
Returns a list of empty directories within the given path.
"""
empty_dirs = []
for root, dirs, files in os.walk(path):
for dir in dirs:
dir_path = os.path.join(root, dir)
try:
if not os.listdir(dir_path):
empty_dirs.append(dir_path)
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {dir_path}")
return empty_dirs
def calculate_total_size_and_files(path):
"""
Calculates the total size of the given directory in bytes
and counts the total number of files within subdirectories.
"""
total_size = 0
total_files = 0
for dirpath, dirnames, filenames in os.walk(path):
if dirpath != path: # Skip counting files in the main directory itself
total_files += len(filenames)
for f in filenames:
fp = os.path.join(dirpath, f)
if not os.path.islink(fp):
try:
total_size += os.path.getsize(fp)
except (OSError, PermissionError):
print(f"⚠️ Could not access file size: {fp}")
return total_size, total_files
def check_las_laz_files(subfolder_path, subfolder_name):
"""
Check for `.las`/`.laz` files in the subfolder.
Ensure filenames contain the subfolder name.
Returns: issues, las_laz_count
"""
files = []
issues = False
las_laz_count = 0
try:
files = [f for f in os.listdir(subfolder_path) if os.path.isfile(os.path.join(subfolder_path, f))]
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {subfolder_path}")
issues = True
las_laz_files = [f for f in files if f.lower().endswith(('.las', '.laz'))]
las_laz_count = len(las_laz_files)
if not las_laz_files:
print(f"❌ Missing `.las` or `.laz` files in: {subfolder_path}")
issues = True
for file in las_laz_files:
if subfolder_name not in file:
print(f"❌ File '{file}' in {subfolder_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
if not issues:
print(f"✅ All `.las`/`.laz` files are present and correctly named in: {subfolder_path} ({las_laz_count} files)")
return issues, las_laz_count
def check_csv_files_in_orbit(subfolder_path, subfolder_name):
"""
Check for `.csv` files in the 'Orbit' subfolder within the given subfolder.
Ensure filenames contain the subfolder name.
Returns: issues, csv_count
"""
orbit_path = os.path.join(subfolder_path, "Orbit")
issues = False
csv_count = 0
if not os.path.exists(orbit_path):
print(f"❌ Missing 'Orbit' subfolder in: {subfolder_path}")
return True, csv_count
files = []
csv_files = []
try:
files = [f for f in os.listdir(orbit_path) if os.path.isfile(os.path.join(orbit_path, f))]
csv_files = [f for f in files if f.lower().endswith('.csv')]
csv_count = len(csv_files)
for file in csv_files:
if subfolder_name not in file:
print(f"❌ CSV '{file}' in {orbit_path} should contain the subfolder name '{subfolder_name}'.")
issues = True
except PermissionError:
print(f"⚠️ Permission denied accessing directory: {orbit_path}")
issues = True
if not csv_files:
print(f"❌ Missing `.csv` files in 'Orbit' subfolder: {orbit_path}")
issues = True
if not issues:
print(f"✅ All `.csv` files are present and correctly named in: {orbit_path} ({csv_count} files)")
return issues, csv_count
def check_files_in_first_subfolders(main_folder):
"""
Checks for `.las`/`.laz` in first-level subfolders and `.csv` files in nested 'Orbit' subfolders.
Ensures they are named correctly according to subfolder naming conventions.
Returns the total distinct count of `.las`/`.laz` and `.csv` files.
"""
issues_found = False
total_las_laz_files = 0
total_csv_files = 0
with os.scandir(main_folder) as entries:
for entry in entries:
if entry.is_dir() and entry.name.startswith('R'):
subfolder_name = entry.name
subfolder_path = entry.path
print(f"\n🔍 Checking files in subfolder: {subfolder_name}")
# Check for `.las`/`.laz` files
las_laz_issues, las_laz_count = check_las_laz_files(subfolder_path, subfolder_name)
total_las_laz_files += las_laz_count
if las_laz_issues:
issues_found = True
# Check for `.csv` files in 'Orbit' subfolder
orbit_issues, csv_count = check_csv_files_in_orbit(subfolder_path, subfolder_name)
total_csv_files += csv_count
if orbit_issues:
issues_found = True
return issues_found, total_las_laz_files, total_csv_files
def main():
while True:
folder_path = input("\n📂 Enter the folder path to check (or type 'exit' to quit): ").strip()
if folder_path.lower() == 'exit':
print("👋 Exiting the script. Goodbye!")
sys.exit()
elif not folder_path:
print("❗ Please enter a valid folder path.")
continue
else:
sanitized_path = sanitize_path(folder_path)
issues_found, total_las_laz_files, total_csv_files = check_files_in_first_subfolders(sanitized_path)
total_size, total_files = calculate_total_size_and_files(sanitized_path)
print(f"\n📊 Directory Analysis Completed:")
print(f"📏 Total size of directory (excluding main): {total_size} bytes")
print(f"📂 Total number of files (excluding main): {total_files}")
print(f"🌐 Total number of .las/.laz files: {total_las_laz_files}")
print(f"📄 Total number of .csv files: {total_csv_files}")
empty_directories = check_empty_dirs(sanitized_path)
if empty_directories:
print("\n⚠️ **Empty Folders/Subfolders Found:**")
for empty_dir in empty_directories:
print(f" - {empty_dir}")
else:
print("\n✅ No empty folders or subfolders.")
if issues_found:
print("\n⚠️ **Some issues were found during the check. Please review the above messages.**")
else:
print("\n🎉 **All files are correctly placed and named.**")
if __name__ == "__main__":
main()
Visual Enhancements:
Emojis and Icons: Included various emojis and icons (📂, 🔍, ✅, ❌, ⚠️, 👋, etc.) to make the output more engaging and visually distinguishable.
Section Headers and Annotations: Used icons to demarcate the sections related to input prompts and analysis results distinctly.
Ensure your terminal supports Unicode to display these icons correctly. In environments like PowerShell 7, this should typically work without issues when using a compatible font.
Key Features of the Script:
Text File Parsing: Extracts the municipality name and date from the first line in the specified format.
Folder Creation: Uses the extracted information to create directories on your desktop.
Date Handling: Creates subfolders for given dates, incrementing by the number of days specified by the user.
Error Handling: Checks for valid file paths and correct user input to ensure smooth execution.
Assumptions:
The .txt file format remains consistent as provided in the example: "LOG LAS NIKAIA 24-04-2024".
The municipality is always third from the last, and the date is last in the line.
The date format in the file is DD-MM-YYYY. Adjust the strptime format if it differs.
import os
from datetime import datetime, timedelta
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
municipality = parts[-3] # Assuming the municipality is always the third last element
date_str = parts[-1] # Assuming the date is the last element
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file: ").strip()
if not os.path.isfile(file_path):
print("❗ The specified path is not a valid file.")
return
municipality, date = extract_info_from_file(file_path)
print(f"Municipality: {municipality}, Date: {date}")
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Script Breakdown:
Main Folder and Base Subfolders: Creates the main folder for the municipality, followed by GEO, ZIP, TRAJ, TXT, DXF, and LAS subfolders.
Date-Based Subfolders: Generates subfolders for the specified date and the consecutive days in both the main folder and the GEO folder.
User-Prompt for Days: Asks the user for the number of additional days, helping extend the folder creation accordingly.
This approach ensures clarity and maintains organized folder structures on your desktop. Adjust the path handling as needed if you run this script in environments other than a desktop setting.
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
municipality = parts[-3] # Assuming the municipality is always the third last element
date_str = parts[-1] # Assuming the date is the last element
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
municipality, date = extract_info_from_file(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Enhancements:
Sanitize Path Function: Added a sanitize_path function to clean the input path by removing any surrounding quotes, allowing users to copy paths enclosed in quotation marks directly into the prompt.
General Input Handling: The script will handle paths and numbers more robustly, reducing errors during script execution.
This version should now fit naturally into workflows where paths might be marked by quotation marks, streamlining the process of entering paths.
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
# Remove all known keywords
filtered_parts = [part for part in parts if part.upper() not in {'LOG', 'LAS'}]
# Assume the municipality is the first "non-keyword" string
if len(filtered_parts) < 2:
raise ValueError("Could not determine municipality or date")
municipality = filtered_parts[0]
date_str = filtered_parts[-1] # Assuming the date is in the expected position
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info_from_file(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Key Adjustments:
Enhanced Parsing Logic: The script filters out known keywords like "LOG" and "LAS" and assumes the first non-keyword entry is the municipality name.
Error Handling: Added a check to ensure sufficient valid data is available for parsing the municipality and date.
Script Robustness: This change makes your script capable of handling varied input formats more gracefully.
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
# Identifiable keywords that should not be part of the municipality name
keywords = {"LOG", "LAS"}
# Filter out known keywords
filtered_parts = [part for part in parts if part.upper() not in keywords]
# Assume the first non-keyword element is the municipality name
# and the last element is the date
if len(filtered_parts) < 2:
raise ValueError("Could not find enough valid elements for municipality and date.")
municipality = filtered_parts[0]
# Attempt to confirm the last element is a date by parsing it
date_format = "%d-%m-%Y"
try:
date_str = filtered_parts[-1]
datetime.strptime(date_str, date_format)
except ValueError:
raise ValueError(f"Last element '{date_str}' is not a valid date in the format {date_format}.")
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info_from_file(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Refinements:
Error Checking: Improved error checking for both the municipality extraction and date parsing.
Flexible Extraction: Assumes that any non-keyword content at the start is the municipality, and it enforces that the last element in the filtered parts list matches a valid date format.
User Feedback: Clear error messages to guide you through understanding what might go wrong during text file parsing.
Please let me know if specific errors persist, and feel free to share the exact message for more precise troubleshooting.
import os
import re
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
# Known keywords to exclude
keywords = {"LOG", "LAS"}
# Use regex to identify a pattern matching a date
date_pattern = re.compile(r"\d{2}[-/]\d{2}[-/]\d{4}|\d{2}[-/]\d{2}[-/]\d{2}")
date_str = None
municipality = None
for part in parts:
# Match the date
if date_pattern.match(part):
date_str = part
break
# Find municipality name by excluding known keywords and date-like strings
potential_names = [part for part in parts if part.upper() not in keywords and not date_pattern.match(part)]
if potential_names:
municipality = potential_names[0]
else:
raise ValueError("Could not determine municipality.")
if not date_str:
raise ValueError("Could not determine date.")
# Adjust date format if necessary (e.g., 03/09/2024 to 03-09-2024)
date_str = date_str.replace('/', '-')
# Attempt to standardize date format with current assumptions
if len(date_str) == 8:
date_str = f"{date_str[:2]}-{date_str[2:4]}-{date_str[4:]}"
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info_from_file(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Key Adjustments:
Date Identification Using Regex: We use a regex pattern to look for date-like strings within the line. This covers common date formats.
Municipality Extraction: Any string not identified as a keyword or a date is considered as a municipality candidate.
Error Messages: Clearer debug messages help pinpoint exactly where the parsing might have failed.
This script should handle variability in the format of the first line of the text file more gracefully. Adjust the date format or regex pattern if your dataset has consistently different formats.
import os
import re
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info_from_filename(filename):
"""
Extracts potential municipality name and date from the filename if needed.
"""
filename_parts = filename.split('_')
potential_municipalities = [part for part in filename_parts if part.isalpha()]
potential_dates = [part for part in filename_parts if part.isdigit()]
municipality = potential_municipalities[0] if potential_municipalities else None
date_str = ""
if potential_dates:
date_part = potential_dates[0]
# Format date part to match DD-MM-YYYY
if len(date_part) == 6:
date_str = f"{date_part[:2]}-{date_part[2:4]}-{date_part[4:]}"
elif len(date_part) == 8:
date_str = f"{date_part[:2]}-{date_part[2:4]}-{date_part[4:]}"
return municipality, date_str
def extract_info_from_file(file_path):
"""
Reads the first line of the file to extract the municipality name and date.
"""
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
# Known keywords to exclude
keywords = {"LOG", "LAS"}
# Use regex to identify a pattern matching a date
date_pattern = re.compile(r"\d{2}[-/ ]\d{2}[-/ ]\d{4}")
date_str = None
municipality = None
for part in parts:
# Match the date
if date_pattern.match(part):
# Convert spaces to dashes for uniform format
date_str = part.replace(" ", "-").replace("/", "-")
break
# Find municipality name by excluding known keywords and date-like strings
potential_names = [part for part in parts if part.upper() not in keywords and not date_pattern.match(part)]
if potential_names:
municipality = potential_names[0]
# Use filename for backup if necessary
if not municipality or not date_str:
filename_municipality, filename_date = extract_info_from_filename(os.path.basename(file_path))
if not municipality:
municipality = filename_municipality
if not date_str:
date_str = filename_date
if not municipality:
raise ValueError("Could not determine municipality.")
if not date_str:
raise ValueError("Could not determine date.")
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info_from_file(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Key Enhancements:
Dual Source Parsing: The script first tries to parse the content of the file. If a date or municipality name is still unclear, it will then check the file name.
Flexible Date Parsing: It can handle dates formatted with spaces, slashes, or dashes.
Error Handling: Additional checks ensure that a valid municipality and date are extracted, otherwise employing the fallback method using the filename.
This script should now handle the various formats in your setup more effectively.
import os
import re
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info(file_path):
"""
Extracts the municipality and date information from both the file content and file name.
"""
# Extract from file name
filename = os.path.basename(file_path)
filename_parts = filename.split('_')
municipality_from_filename = filename_parts[0]
date_from_filename = filename_parts[-1].split('.')[0] # Strip extension
# Format the extracted date from filename
if len(date_from_filename) == 6:
date_from_filename = f"{date_from_filename[:2]}-{date_from_filename[2:4]}-20{date_from_filename[4:]}" # Assuming year needs prepending '20'
# Extract from file content
with open(file_path, 'r') as file:
first_line = file.readline().strip()
# Assume the municipality is the first part.
parts = first_line.split()
if len(parts) >= 4: # Ensure we have enough parts
municipality_from_content = parts[0]
date_str = f"{parts[1]}-{parts[2]}-{parts[3]}"
else:
raise ValueError("File content is not in the expected format.")
# Confirm the validity of the content and determine defaults
municipality = municipality_from_content or municipality_from_filename
date_str = date_str if len(parts) >= 4 else date_from_filename
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Script Breakdown:
Filename Parsing: The script now extracts the municipality and date from the filename, assuming these follow a given structure.
File Content Parsing: Extracts additional information from the content, checking both sources for robustness. It uses the correct part ordering based on your example.
Date Validation: Employs the datetime.strptime method to ensure date parsing works correctly for the format provided.
This strategy checks both the filename and content, adapting to where the data is most accurately presented. Adjustments have been made based on your specification. Let me know if you need further modifications!
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info(file_path):
"""
Extracts the municipality and date from both the file content and the filename if necessary.
"""
# Start by assuming the filename contains backup info
filename = os.path.basename(file_path)
filename_parts = filename.split('_')
municipality_from_filename = filename_parts[0]
date_from_filename = filename_parts[-1].split('.')[0] # Strip extension and any other text
# Format the extracted date from filename
if len(date_from_filename) == 6:
date_from_filename = f"{date_from_filename[:2]}-{date_from_filename[2:4]}-20{date_from_filename[4:]}"
# Extract from file content
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
if len(parts) == 4: # Assuming a consistent format
municipality_from_content = parts[0]
date_str_from_content = f"{parts[1]}-{parts[2]}-{parts[3]}"
else:
municipality_from_content = None
date_str_from_content = None
print(f"⚠️ Note: Unable to parse both municipality and date directly from file content. Using defaults from filename.")
# Determine which to use
municipality = municipality_from_content or municipality_from_filename
date_str = date_str_from_content or date_from_filename
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, num_days):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
start_date_obj = datetime.strptime(start_date, "%d-%m-%Y")
dates = [(start_date_obj + timedelta(days=i)).strftime("%d-%m-%Y") for i in range(num_days + 1)]
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
try:
num_days = int(input("Enter the number of additional days to create folders for: ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of days.")
return
create_folder_structure(municipality, date, num_days)
if __name__ == "__main__":
main()
Key Adjustments:
File Content Parsing: The script tries to extract the municipality and date from the file content but defaults to using filename data if the content doesn't fit the expected structure.
Diagnostics: Prints additional messages to indicate when it's falling back to using the file name data.
Dual Source Reliability: Incorporates logic for consistent extraction of data from two potential sources, to handle edge cases more effectively.
This approach seeks to handle exceptions by providing alternatives when data isn't formatted as expected in either source.
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
if (input_path.startswith('"') and input_path.endswith('"')) or \
(input_path.startswith("'") and input_path.endswith("'")):
return input_path[1:-1]
return input_path
def extract_info(file_path):
"""
Extracts the municipality and date from both the file content and the filename if necessary.
"""
# Start by assuming the filename contains backup info
filename = os.path.basename(file_path)
filename_parts = filename.split('_')
municipality_from_filename = filename_parts[0]
date_from_filename = filename_parts[-1].split('.')[0] # Strip extension and any other text
# Format the extracted date from filename
if len(date_from_filename) == 6:
date_from_filename = f"{date_from_filename[:2]}-{date_from_filename[2:4]}-20{date_from_filename[4:]}"
# Extract from file content
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
if len(parts) == 4: # Assuming a consistent format
municipality_from_content = parts[0]
date_str_from_content = f"{parts[1]}-{parts[2]}-{parts[3]}"
else:
municipality_from_content = None
date_str_from_content = None
print(f"⚠️ Note: Unable to parse both municipality and date directly from file content. Using defaults from filename.")
# Determine which to use
municipality = municipality_from_content or municipality_from_filename
date_str = date_str_from_content or date_from_filename
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_main_and_geo_subfolders(main_folder_path, dates):
"""
Creates the GEO subfolder structure with date subfolders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, additional_dates):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
dates = [start_date] + additional_dates
create_main_and_geo_subfolders(main_folder_path, dates)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
additional_dates_input = input("Enter any additional dates for folders (comma-separated, in DD-MM-YYYY format): ").strip()
additional_dates = []
if additional_dates_input:
extra_dates_str = additional_dates_input.split(',')
for date_str in extra_dates_str:
date_str = date_str.strip()
try:
# Validate the dates and add to the list
datetime.strptime(date_str, "%d-%m-%Y")
additional_dates.append(date_str)
except ValueError:
print(f"❗ Invalid date format: '{date_str}'. Please enter dates in DD-MM-YYYY format.")
create_folder_structure(municipality, date, additional_dates)
if __name__ == "__main__":
main()
How This Script Works:
User Prompt for Additional Dates: After identifying the initial date from the file, the script prompts you to enter any additional dates.
Input Format: Dates should be entered in DD-MM-YYYY format and separated by commas.
Validation: The input dates are validated for format correctness before folder creation, ensuring that only valid dates are processed.
Custom Flexibility: This method allows complete flexibility in choosing specific dates for folder creation, letting you skip or add dates as needed.
Non-Standard SSDs: Depending on the MacBook model, Apple often uses proprietary SSDs, which can limit your options for replacement drives unless you use an adapter or a compatible third-party SSD.
Firmware Locks: If your MacBook is protected by a firmware lock (often set for security), you may need to disable it temporarily to complete the OS installation.
Apple's T2 Chip (if present): Newer models with the T2 security chip feature added layers of software integrity checks. These require a network connection to verify the macOS installation or use a specific macOS version.
Data Migration: If you had important data on your old SSD, ensure you have backups. Migration can be done via Time Machine, or externally copied data if the old SSD is accessible via an adapter.
Steps to Reinstall macOS After SSD Replacement:
Ensure all hardware connections are securely reassembled.
Boot into Internet Recovery or use a bootable USB.
Format the new SSD using Disk Utility to APFS (for macOS High Sierra or later) or Mac OS Extended (Journaled) (for older macOS versions).
Follow prompts to reinstall macOS on the newly formatted SSD.
The process should be carefully followed, and if uncomfortable with any steps, consider seeking professional assistance, especially with handling sensitive hardware.
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
return input_path.strip('"').strip("'")
def extract_info(file_path):
"""
Extracts the municipality and date information from both the file content and file name.
"""
# Start by assuming the filename contains backup info
filename = os.path.basename(file_path)
filename_parts = filename.split('_')
municipality_from_filename = filename_parts[0]
date_from_filename = filename_parts[-1].split('.')[0] # Strip extension and any other text
# Format the extracted date from filename
if len(date_from_filename) == 6:
date_from_filename = f"{date_from_filename[:2]}-{date_from_filename[2:4]}-20{date_from_filename[4:]}"
# Extract from file content
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
if len(parts) == 4: # Assuming a consistent format
municipality_from_content = parts[0]
date_str_from_content = f"{parts[1]}-{parts[2]}-{parts[3]}"
else:
municipality_from_content = None
date_str_from_content = None
print(f"⚠️ Note: Unable to parse both municipality and date directly from file content. Using defaults from filename.")
# Determine which to use
municipality = municipality_from_content or municipality_from_filename
date_str = date_str_from_content or date_from_filename
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_run_subfolders(date_folder_path, num_runs):
"""
Creates subfolders named R1, R2, ..., RN inside the given date folder.
"""
for i in range(1, num_runs + 1):
run_folder_path = os.path.join(date_folder_path, f"R{i}")
os.makedirs(run_folder_path, exist_ok=True)
print(f"📂 Created run subfolder: {run_folder_path}")
def create_main_and_geo_subfolders(main_folder_path, dates, num_runs):
"""
Creates the GEO subfolder structure with date subfolders and RUN folders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str in dates:
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
create_run_subfolders(date_folder_path, num_runs)
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
create_run_subfolders(geo_date_folder_path, num_runs)
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, start_date, additional_dates, num_runs):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
dates = [start_date] + additional_dates
create_main_and_geo_subfolders(main_folder_path, dates, num_runs)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, date = extract_info(sanitized_path)
print(f"Municipality: {municipality}, Date: {date}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
additional_dates_input = input("Enter any additional dates for folders (comma-separated, in DD-MM-YYYY format): ").strip()
additional_dates = []
if additional_dates_input:
extra_dates_str = additional_dates_input.split(',')
for date_str in extra_dates_str:
date_str = date_str.strip()
try:
datetime.strptime(date_str, "%d-%m-%Y")
additional_dates.append(date_str)
except ValueError:
print(f"❗ Invalid date format: '{date_str}'. Please enter dates in DD-MM-YYYY format.")
try:
num_runs = int(input("Enter the number of 'R' subfolders to create for each date (e.g., 3 for R1, R2, R3): ").strip())
except ValueError:
print("❗ Please enter a valid number for the number of 'R' subfolders.")
return
create_folder_structure(municipality, date, additional_dates, num_runs)
if __name__ == "__main__":
main()
Enhancements Made:
Prompt for "R" Folders: The script now includes a prompt asking how many R folders you'd like to create for each date folder (e.g., R1, R2, R3, etc.).
Nested Folder Creation: R folders are created within both the main date and GEO date folders.
User Input Flexibility: Provides the flexibility needed to customize folder structures as required for different projects or organizational needs.
import os
from datetime import datetime, timedelta
def sanitize_path(input_path):
"""
Removes surrounding quotes from the input path if present.
"""
return input_path.strip('"').strip("'")
def extract_info(file_path):
"""
Extracts the municipality and date information from both the file content and file name.
"""
# Start by assuming the filename contains backup info
filename = os.path.basename(file_path)
filename_parts = filename.split('_')
municipality_from_filename = filename_parts[0]
date_from_filename = filename_parts[-1].split('.')[0] # Strip extension and any other text
# Format the extracted date from filename
if len(date_from_filename) == 6:
date_from_filename = f"{date_from_filename[:2]}-{date_from_filename[2:4]}-20{date_from_filename[4:]}"
# Extract from file content
with open(file_path, 'r') as file:
first_line = file.readline().strip()
parts = first_line.split()
if len(parts) == 4: # Assuming a consistent format
municipality_from_content = parts[0]
date_str_from_content = f"{parts[1]}-{parts[2]}-{parts[3]}"
else:
municipality_from_content = None
date_str_from_content = None
print(f"⚠️ Note: Unable to parse both municipality and date directly from file content. Using defaults from filename.")
# Determine which to use
municipality = municipality_from_content or municipality_from_filename
date_str = date_str_from_content or date_from_filename
try:
datetime.strptime(date_str, "%d-%m-%Y")
except ValueError:
raise ValueError(f"Identified string '{date_str}' is not a valid date.")
return municipality, date_str
def create_run_subfolders(date_folder_path, num_runs):
"""
Creates subfolders named R1, R2, ..., RN inside the given date folder.
"""
for i in range(1, num_runs + 1):
run_folder_path = os.path.join(date_folder_path, f"R{i}")
os.makedirs(run_folder_path, exist_ok=True)
print(f"📂 Created run subfolder: {run_folder_path}")
def create_main_and_geo_subfolders(main_folder_path, dates, runs_per_date):
"""
Creates the GEO subfolder structure with date subfolders and RUN folders.
"""
geo_folder_path = os.path.join(main_folder_path, "GEO")
os.makedirs(geo_folder_path, exist_ok=True)
print(f"📂 Created GEO folder: {geo_folder_path}")
for date_str, num_runs in zip(dates, runs_per_date):
date_folder_path = os.path.join(main_folder_path, date_str)
os.makedirs(date_folder_path, exist_ok=True)
print(f"📂 Created date subfolder: {date_folder_path}")
create_run_subfolders(date_folder_path, num_runs)
geo_date_folder_path = os.path.join(geo_folder_path, date_str)
os.makedirs(geo_date_folder_path, exist_ok=True)
print(f"📂 Created GEO date subfolder: {geo_date_folder_path}")
create_run_subfolders(geo_date_folder_path, num_runs)
def create_additional_subfolders(main_folder_path):
"""
Creates additional subfolders: ZIP, TRAJ, TXT, DXF, LAS.
"""
subfolders = ["ZIP", "TRAJ", "TXT", "DXF", "LAS"]
for folder_name in subfolders:
folder_path = os.path.join(main_folder_path, folder_name)
os.makedirs(folder_path, exist_ok=True)
print(f"📂 Created {folder_name} folder: {folder_path}")
def create_folder_structure(municipality, dates, runs_per_date):
"""
Creates the folder structure on the desktop.
"""
desktop_path = os.path.join(os.path.expanduser("~"), "Desktop")
main_folder_path = os.path.join(desktop_path, municipality)
try:
os.makedirs(main_folder_path, exist_ok=True)
print(f"✅ Created main folder: {main_folder_path}")
create_main_and_geo_subfolders(main_folder_path, dates, runs_per_date)
create_additional_subfolders(main_folder_path)
except Exception as e:
print(f"❌ Error creating folders: {e}")
def main():
file_path = input("Enter the path to the .txt file (in quotes if needed): ").strip()
sanitized_path = sanitize_path(file_path)
if not os.path.isfile(sanitized_path):
print("❗ The specified path is not a valid file.")
return
try:
municipality, initial_date_str = extract_info(sanitized_path)
print(f"Municipality: {municipality}, Date: {initial_date_str}")
except ValueError as e:
print(f"❗ Error reading file: {e}")
return
additional_days_input = input("Enter any additional days for folders within the same month and year (comma-separated): ").strip()
additional_dates = []
runs_per_date = []
# Convert initial date to datetime object for reference
initial_date = datetime.strptime(initial_date_str, "%d-%m-%Y")
if additional_days_input:
extra_days_str = additional_days_input.split(',')
for day in extra_days_str:
day = day.strip()
try:
# Only change the day, keep the same month and year
new_date = initial_date.replace(day=int(day))
date_str = new_date.strftime("%d-%m-%Y")
additional_dates.append(date_str)
except ValueError:
print(f"❗ Invalid day entered: '{day}'. Please enter valid day numbers for the current month/year.")
# Always include the initial date
all_dates = [initial_date_str] + additional_dates
# Prompt for number of 'R' folders for each date
for date in all_dates:
try:
num_runs = int(input(f"Enter the number of 'R' subfolders for {date} (e.g., 3 for R1, R2, R3): ").strip())
runs_per_date.append(num_runs)
except ValueError:
print(f"❗ Please enter a valid number for 'R' subfolders for {date}. Defaulting to 0.")
runs_per_date.append(0)
create_folder_structure(municipality, all_dates, runs_per_date)
if __name__ == "__main__":
main()
Improvements Made:
Date Input Simplification: You can now input only day numbers for additional dates which keep the same month and year. This is based on the initial date.
Custom 'R' Folder Count: The script prompts you for the number of 'R' folders for each date, allowing varied structure for each.
Input Validation: Includes checking for valid day numbers and robust input handling for creating structured folders.