python 文件更新_python-如何仅将更新的文件从文件夹移动到...

我建议使用msw的建议,即使用os.stat.

理想情况下,您可以检查最近修改了哪些对象,检查源文件夹和目标文件夹中dll文件的st_mtime值,并查看哪个更大.如果st_mtime用于您的源文件夹文件大于目标文件夹文件,则将其移动,否则可以忽略它们.

该答案假定您的python文件与src和dest目录位于同一目录级别.以下代码背后的逻辑应向您展示如何更新文件:

根目录

Root

|

├───dest

├───src

└───updater.py

updater.py

import os

import shutil

# Imported for convenience

from collections import namedtuple

# Main function, so this can act like a script

if __name__ == '__main__':

ROOT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__))) # Root directory

file_change_times_dest = [] # List of files from destination folder

file_change_times_src = [] # List of files from source folder

# Nameed tuple to ease writing code

FileInformation = namedtuple('FileInformation', ['file_path', 'file_name', 'last_modified'])

# Loop through files in destination folder to collect information

for dirpath, dirs, files in os.walk(os.path.join(ROOT_DIR, 'dest')):

for file in files:

# getting file path

file_path = os.path.join(dirpath, file)

# getting file change info and casting it to FileInformation type

file_change_times_dest.append(FileInformation(file_path, file, os.stat(file_path).st_mtime))

# Loop through source folder, same logic

for dirpath, dirs, files in os.walk(os.path.join(ROOT_DIR, 'src')):

for file in files:

file_path = os.path.join(dirpath, file)

file_change_times_src.append(FileInformation(file_path, file,os.stat(file_path).st_mtime))

# Comparing the two, using Zip to combine the two lists into a tuple

for file_comp in zip(file_change_times_dest, file_change_times_src):

# Settings variables for 0 and 1 to make writing code easier

_DEST = 0

_SRC = 1

# File comparison, to see if file name is the same, since we want to update

if file_comp[_SRC].file_name == file_comp[_DEST].file_name:

# If the last modified is greater for source, then we copy

if file_comp[_SRC].last_modified > file_comp[_DEST].last_modified:

shutil.copy(file_comp[_SRC].file_path, file_comp[_DEST].file_path)

print("File moved") # Just for checking

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值