Популярное

Музыка Кино и Анимация Автомобили Животные Спорт Путешествия Игры Юмор

Интересные видео

2025 Сериалы Трейлеры Новости Как сделать Видеоуроки Diy своими руками

Топ запросов

смотреть а4 schoolboy runaway турецкий сериал смотреть мультфильмы эдисон
dTub
Скачать

Delete files based on modified date using Python

Автор: Analyst's Corner

Загружено: 2023-01-14

Просмотров: 784

Описание:

Code link: https://github.com/oscarito-taquito/y...

Free uDemy Courses: https://www.udemy.com/user/oscar-2330/
Buy me a coffee: https://buymeacoffee.com/oscarito
Affiliate Savings: https://analystscorner.net/affiliates...


Python Script to Manage File Information and Clean Up Old Files

Description:

Today, I'm happy to share with you a Python script I wrote that helps manage and clean up old files from your computer. This script is perfect for anyone who wants to keep their digital workspace organized and clutter-free. Whether you're a college freshman like me or a seasoned programmer, this tutorial will guide you through understanding and using the script. So, let's dive in!

Video Overview

In this video, I'll walk you through a Python script that does the following:
1. *Gets the current working directory* - We'll use `os.getcwd()` to find out where we are currently working.
2. *Lists all files in the directory* - Using `os.listdir()`, we'll gather all the files in our current directory.
3. *Captures file information* - We'll create a function to retrieve creation and modification dates of each file.
4. *Calculates the age of files* - We'll determine how many days old each file is.
5. *Sorts files by modification date* - Organizing files based on when they were last modified.
6. *Decides whether to delete or keep files* - Based on the age of the files, we'll decide which files to keep and which to remove.

Script Breakdown

Here's a detailed look at the script:

#### Importing Libraries

```python
import os
import datetime as dt
```
We start by importing the necessary libraries. `os` is used for interacting with the operating system, and `datetime` helps us work with dates and times.

#### Getting Current Directory and File List

```python
cur_path = os.getcwd()
files = os.listdir(cur_path)
now = dt.datetime.today()
```
We retrieve the current directory path using `os.getcwd()` and list all the files in that directory with `os.listdir()`. We also get the current date and time with `dt.datetime.today()`.

#### Capturing File Information

```python
def file_info(cd, file_list, today):
file_dict = {}
for file in file_list:
file_path = os.path.join(cd, file)
created = os.stat(file_path)
created = dt.datetime.fromtimestamp(created.st_birthtime)
modified = dt.datetime.fromtimestamp(os.path.getmtime(file_path))
since_created = int((today - created).total_seconds() / (60 * 60 * 24))
since_mod = int((today - modified).total_seconds() / (60 * 60 * 24))
file_dict[file] = [file_path, file, f"{created}", f"{modified}", since_created, since_mod]
return file_dict
```
We define a function `file_info()` that takes the current directory, a list of files, and the current date as arguments. This function gathers information about each file, including its path, creation date, modification date, and age in days. It stores this information in a dictionary.

#### Sorting Files by Modification Date

```python
dir_listing = file_info(cur_path, files, now)
print(dir_listing)
dir_listing_sort = sorted(dir_listing.items(), key=lambda x: x[1][5])
```
We call the `file_info()` function and print the resulting dictionary. Then, we sort the files based on their modification dates.

#### Deciding to Delete or Keep Files

```python
for k, v in dir_listing_sort:
print(v[1], v[5])
if v[5] gt 250:
os.remove(v[0])
print('Delete File')
else:
print('Keep File')
```
We loop through the sorted file list and decide whether to delete or keep each file based on its age. If a file is older than 250 days, we mark it for deletion. Otherwise, we keep it.

Conclusion

I hope you found this tutorial helpful! This script is a great starting point for managing and organizing your files. Feel free to modify and expand upon it to suit your needs. If you have any questions or suggestions, leave a comment below. Don't forget to like, share, and subscribe for more awesome content!

*Tags:* Python, File Management, Cleanup Script, Organize Files, Python Tutorial, College Freshman, Programming Basics, Python for Beginners, Learn Python, Coding Tips, Digital Organization, File Information, Delete Old Files, Python Script Tutorial, os module, datetime module

Thanks for watching!

Delete files based on modified date using Python

Поделиться в:

Доступные форматы для скачивания:

Скачать видео mp4

  • Информация по загрузке:

Скачать аудио mp3

Похожие видео

Filtering .log files, with cat, grep, cut, sort, and uniq

Filtering .log files, with cat, grep, cut, sort, and uniq

How to Easily Find Keywords in a Document with KeyBERT in Python

How to Easily Find Keywords in a Document with KeyBERT in Python

Learned Python in 2.5 Hours (With ANIMATIONS) | Full Course for Beginners

Learned Python in 2.5 Hours (With ANIMATIONS) | Full Course for Beginners

Организация файлов с помощью Python: переименование, перемещение, копирование и удаление файлов и...

Организация файлов с помощью Python: переименование, перемещение, копирование и удаление файлов и...

Подробное изучение обработки ошибок в Python: исключения, модульное тестирование, логирование.

Подробное изучение обработки ошибок в Python: исключения, модульное тестирование, логирование.

Почему я перешел на Zed?

Почему я перешел на Zed?

Python Script to Delete all files which are older than x days

Python Script to Delete all files which are older than x days

Scripting with Python - Modify a TXT file

Scripting with Python - Modify a TXT file

Python Tutorial: Logging Basics - Logging to Files, Setting Levels, and Formatting

Python Tutorial: Logging Basics - Logging to Files, Setting Levels, and Formatting

Making an Amazon Price Tracker Using Python in Less Than 30 Lines

Making an Amazon Price Tracker Using Python in Less Than 30 Lines

Как читать текстовый файл .txt на Python! Извлечение данных, фильтрация и изменение информации!

Как читать текстовый файл .txt на Python! Извлечение данных, фильтрация и изменение информации!

Day in the Life of a Data Analyst

Day in the Life of a Data Analyst

5 IMPRESSIVE Python Resume Projects (You Can Finish in A Weekend)

5 IMPRESSIVE Python Resume Projects (You Can Finish in A Weekend)

The Windows 11 Disaster That's Killing Microsoft

The Windows 11 Disaster That's Killing Microsoft

Python - Read from multiple files & Regex search pattern in files

Python - Read from multiple files & Regex search pattern in files

Visualizing Excel Files Easily With Python

Visualizing Excel Files Easily With Python

WHAT Is

WHAT Is "Glob" In Python?! (It's Actually Very Useful!)

How To Delete All Files with Specific Extension in a Folder - Python

How To Delete All Files with Specific Extension in a Folder - Python

Python Example 2: How to create new folders (directories) using Python scripts?

Python Example 2: How to create new folders (directories) using Python scripts?

Building an Automated File Sorter in File Explorer using Python | Python Projects for Beginners

Building an Automated File Sorter in File Explorer using Python | Python Projects for Beginners

© 2025 dtub. Все права защищены.



  • Контакты
  • О нас
  • Политика конфиденциальности



Контакты для правообладателей: infodtube@gmail.com