Py学习  »  Python

如果文件在一段时间内未打开,请将其剪切到另一个文件夹中-python脚本

Naturaleza • 3 年前 • 1730 次点击  

我有一个脚本,在一个文件夹中生成一堆文件。随着文件堆的增加,我的脚本变得越来越慢。我想创建一个python脚本,它将查看文件夹和每个创建的文件,并且在半小时内没有打开(我需要这个条件,因为我的脚本在创建之后正在读取它们),以便与其他文件夹一起移动(剪切)。我熟悉熊猫和努比,但不熟悉这个地区。。有人能帮我吗? 建立 this answer 然而,它并没有帮助我实现我想要的。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/130088
 
1730 次点击  
文章 [ 2 ]  |  最新文章 3 年前
Naturaleza
Reply   •   1 楼
Naturaleza    3 年前
import os
import shutil
import time
import datetime
from datetime import timedelta
def list_files(folder):
    # your attempt
    return os.listdir(folder)

os.chdir('source path')
destination_folder = 'destination_folder'
source_folder = 'source folder'
folder = os.getenv('source folder')
for filename in list_files(folder):
    last_modified = os.path.getmtime(filename)
    local_time = time.ctime(last_modified)
    python_local_time = datetime.datetime.strptime(local_time, "%a %b %d %H:%M:%S %Y")
    now = datetime.datetime.strptime(time.ctime(), "%a %b %d %H:%M:%S %Y")
    if  now - python_local_time > timedelta(days=10):
       shutil.move(source_folder + filename, destination_folder + filename)
hc_dev
Reply   •   2 楼
hc_dev    3 年前

根据所需的文件时间戳,例如,请参见:

How to get the first accessed time file was created along with the last modified time?

举个粗略的例子:

  • 打印temp文件夹中的所有文件(基于OS的环境变量)及其最后修改的时间戳
import os

def list_files(folder):
    # your attempt
    return os.listdir(folder)


folder = os.getenv('TEMP')
for filename in list_files(folder):
    last_modified = os.path.getmtime(filename)
    print(f"{filename} last modified: {last_modified}")

打印出如下几行:

.Xdefaults上次修改:1531860388.7936974

.gnome上次修改:1588427978.179283