Created
May 2, 2024 06:13
-
-
Save maarten-betman/447b3fae946a0c74764ed812a5ba6e8a to your computer and use it in GitHub Desktop.
Create overview of files on a hard drive and storing file info in a Access database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from pathlib import Path | |
| import pyodbc | |
| from datetime import datetime | |
| def get_file_details(startpath): | |
| file_details = [] | |
| start_path = Path(startpath) | |
| for file_path in start_path.rglob('*'): | |
| if file_path.is_file(): | |
| try: | |
| stats = file_path.stat() | |
| file_details.append({ | |
| 'name': file_path.name, | |
| 'path': str(file_path.parent), | |
| 'size': stats.st_size, | |
| 'created': datetime.fromtimestamp(stats.st_ctime).strftime('%Y-%m-%d %H:%M:%S'), | |
| 'modified': datetime.fromtimestamp(stats.st_mtime).strftime('%Y-%m-%d %H:%M:%S') | |
| }) | |
| except Exception as e: | |
| print(f"Error processing file {file_path}: {e}") | |
| return file_details | |
| def connect_to_access(db_file): | |
| conn_str = ( | |
| r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};' | |
| r'DBQ=' + str(Path(db_file)) + ';' | |
| ) | |
| cnxn = pyodbc.connect(conn_str) | |
| return cnxn | |
| def write_to_database(cnxn, file_details): | |
| cursor = cnxn.cursor() | |
| for file in file_details: | |
| cursor.execute("INSERT INTO FileInfo (FileName, FilePath, FileSize, DateCreated, DateModified) VALUES (?, ?, ?, ?, ?)", | |
| (file['name'], file['path'], file['size'], file['created'], file['modified'])) | |
| cnxn.commit() | |
| drive_path = 'D:\\' # Change this to the path of your external hard drive | |
| database_path = 'path\\to\\your\\database.accdb' # Change this to the path of your Access database | |
| file_details = get_file_details(drive_path) | |
| cnxn = connect_to_access(database_path) | |
| write_to_database(cnxn, file_details) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment