<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>脚本入门 &#8211; mylogs.cn</title>
	<atom:link href="https://mylogs.cn/tag/%e8%84%9a%e6%9c%ac%e5%85%a5%e9%97%a8/feed/" rel="self" type="application/rss+xml" />
	<link>https://mylogs.cn</link>
	<description>发现、记录、分享</description>
	<lastBuildDate>Mon, 10 Aug 2026 20:32:52 +0000</lastBuildDate>
	<language>zh-Hans</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>一段 Python 脚本，文件丢进去就自动归位</title>
		<link>https://mylogs.cn/%e4%b8%80%e6%ae%b5-python-%e8%84%9a%e6%9c%ac%ef%bc%8c%e6%96%87%e4%bb%b6%e4%b8%a2%e8%bf%9b%e5%8e%bb%e5%b0%b1%e8%87%aa%e5%8a%a8%e5%bd%92%e4%bd%8d/</link>
		
		<dc:creator><![CDATA[steve, zhang]]></dc:creator>
		<pubDate>Mon, 10 Aug 2026 20:32:52 +0000</pubDate>
				<category><![CDATA[经验与技巧]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[效率工具]]></category>
		<category><![CDATA[文件整理]]></category>
		<category><![CDATA[脚本入门]]></category>
		<category><![CDATA[自动化]]></category>
		<guid isPermaLink="false">https://mylogs.cn/%e4%b8%80%e6%ae%b5-python-%e8%84%9a%e6%9c%ac%ef%bc%8c%e6%96%87%e4%bb%b6%e4%b8%a2%e8%bf%9b%e5%8e%bb%e5%b0%b1%e8%87%aa%e5%8a%a8%e5%bd%92%e4%bd%8d/</guid>

					<description><![CDATA[从相机导出的照片、从压缩包里解出的图片、游戏机传过来的截图，最后往往全都躺在同一个文件夹里，几百个文件挤成一团 [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p class="wp-block-paragraph">从相机导出的照片、从压缩包里解出的图片、游戏机传过来的截图，最后往往全都躺在同一个文件夹里，几百个文件挤成一团。手动整理这件事，多数人坚持不过三天。系统自带的自动整理规则又太死板，想按文件名里的日期分层建目录，基本无从下手。</p>



<figure data-wp-context="{&quot;imageId&quot;:&quot;6a7a6873c157c&quot;}" data-wp-interactive="core/image" data-wp-key="6a7a6873c157c" class="wp-block-image size-large aligncenter wp-lightbox-container"><img fetchpriority="high" decoding="async" width="1200" height="750" data-wp-class--hide="state.isContentHidden" data-wp-class--show="state.isContentVisible" data-wp-init="callbacks.setButtonStyles" data-wp-on--click="actions.showLightbox" data-wp-on--load="callbacks.setButtonStyles" data-wp-on--pointerdown="actions.preloadImage" data-wp-on--pointerenter="actions.preloadImageWithDelay" data-wp-on--pointerleave="actions.cancelPreload" data-wp-on-window--resize="callbacks.setButtonStyles" src="https://mylogs.cn/wp-content/uploads/2026/08/8a5339da1be29c657b81f820d0fe2823_header.webp" alt="一段 Python 脚本，文件丢进去就自动归位" class="wp-image-4361" style="max-width:100%;height:auto;" srcset="https://mylogs.cn/wp-content/uploads/2026/08/8a5339da1be29c657b81f820d0fe2823_header.webp 1200w, https://mylogs.cn/wp-content/uploads/2026/08/8a5339da1be29c657b81f820d0fe2823_header-300x188.webp 300w, https://mylogs.cn/wp-content/uploads/2026/08/8a5339da1be29c657b81f820d0fe2823_header-1024x640.webp 1024w, https://mylogs.cn/wp-content/uploads/2026/08/8a5339da1be29c657b81f820d0fe2823_header-768x480.webp 768w" sizes="(max-width: 1200px) 100vw, 1200px" /><button
			class="lightbox-trigger"
			type="button"
			aria-haspopup="dialog"
			data-wp-bind--aria-label="state.thisImage.triggerButtonAriaLabel"
			data-wp-init="callbacks.initTriggerButton"
			data-wp-on--click="actions.showLightbox"
			data-wp-style--right="state.thisImage.buttonRight"
			data-wp-style--top="state.thisImage.buttonTop"
		>
			<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" fill="none" viewBox="0 0 12 12">
				<path fill="#fff" d="M2 0a2 2 0 0 0-2 2v2h1.5V2a.5.5 0 0 1 .5-.5h2V0H2Zm2 10.5H2a.5.5 0 0 1-.5-.5V8H0v2a2 2 0 0 0 2 2h2v-1.5ZM8 12v-1.5h2a.5.5 0 0 0 .5-.5V8H12v2a2 2 0 0 1-2 2H8Zm2-12a2 2 0 0 1 2 2v2h-1.5V2a.5.5 0 0 0-.5-.5H8V0h2Z" />
			</svg>
		</button><figcaption class="wp-element-caption">图片来源：How-To Geek</figcaption></figure>





<p class="wp-block-paragraph">用 Python 搭一个「落地文件夹」是更灵活的解法：指定一个目录，任何文件丢进去，脚本立刻识别、改名、按规则挪到该去的位置。关键在于不用笨办法。最原始的思路是写个死循环反复列目录、比对差异，既费电又不及时。Watchdog 这个库直接调用操作系统的原生接口——Linux 上是 inotify，macOS 上是 FSEvents——由系统在文件变化时主动通知程序。</p>



<h2 class="wp-block-heading">一、先把环境搭好</h2>



<p class="wp-block-paragraph">How-To Geek 撰稿人 Bobby Jack 强调，虚拟环境这一步别省，否则后面会后悔：</p>



<pre class="wp-block-code"><code>mkdir my-project
cd my-project
python3 -m venv venv
source venv/bin/activate</code></pre>



<p class="wp-block-paragraph">Windows 下激活命令换成 <code>venv\Scripts\activate</code>。然后安装库：</p>



<pre class="wp-block-code"><code>python -m pip install watchdog</code></pre>



<h2 class="wp-block-heading">二、跑通最小示例</h2>



<p class="wp-block-paragraph">先别管细节，把下面这段跑起来，确认监听有效：</p>



<pre class="wp-block-code"><code>import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler

if __name__ == &quot;__main__&quot;:
    logging.basicConfig(level=logging.INFO)
    event_handler = LoggingEventHandler()

    observer = Observer()
    observer.schedule(event_handler, &#x27;.&#x27;, recursive=True)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()

    observer.join()</code></pre>



<p class="wp-block-paragraph">运行后它会盯住当前目录。此时新建一个空文件，或者把某个文件改名，控制台就会打印出对应的事件日志。</p>



<h2 class="wp-block-heading">三、按文件名里的日期自动分层</h2>



<p class="wp-block-paragraph">Bobby Jack 的实际需求是整理游戏机截图。这类文件名形如 <code>2025010409204300-D796833F72011BDFC9868896D061B51F.jpg</code>，前 14 位依次是年、月、日、时、分、秒，接着两位用于区分同一秒内的多张，短横线后是 32 位十六进制的软件标识，扩展名固定为 .jpg（同一批里的 .mp4 视频直接忽略）。目标是把它们整理成「年/月/日」的目录结构。</p>



<p class="wp-block-paragraph">先定义好三个常量和一条正则表达式，括号里的捕获组分别对应年、月、日和剩余部分：</p>



<pre class="wp-block-code"><code>import os
import time
import re
from pathlib import Path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

WATCH_FOLDER = Path(&quot;/tmp&quot;)
TARGET_FOLDER = Path(&quot;/Users/bobby/Pictures/switch-screenshots&quot;)
PATTERN = r&quot;^([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{8}-[A-F0-9]{32}\.jpg)$&quot;</code></pre>



<p class="wp-block-paragraph">处理逻辑写在事件处理类里，覆盖父类的 <code>on_created</code> 方法：</p>



<pre class="wp-block-code"><code>class FileDropHandler(FileSystemEventHandler):
    def on_created(self, event):
        if event.is_directory:
            return

        file_path = Path(event.src_path)

        if not re.match(PATTERN, file_path.name):
            return

        self._wait_for_file_copy(file_path)
        self.process_file(file_path)

    def process_file(self, file_path):
        try:
            search = re.search(PATTERN, file_path.name)
            if not search:
                return

            target = TARGET_FOLDER / search.group(1)
            target = target / search.group(2)
            target = target / search.group(3)

            target.mkdir(parents=True, exist_ok=True)
            file_path.move(target / search.group(4))

            print(f&quot;Moved: {file_path.name}&quot;)
        except Exception as e:
            print(f&quot;Error processing {file_path.name}: {e}&quot;)</code></pre>



<p class="wp-block-paragraph">其中 <code>_wait_for_file_copy</code> 是一段用于确认文件已经复制完毕的检查代码，作用是避免在文件还没写完时就去搬动它。主程序部分与前面的示例几乎一致，只是把处理器换成 <code>FileDropHandler()</code>，并把监听路径指向 <code>WATCH_FOLDER</code>。</p>



<h2 class="wp-block-heading">四、改成自己的规则</h2>



<p class="wp-block-paragraph">监听路径和目标路径目前是写死的，做成命令行参数会更好用。真正需要动的只有那条正则表达式：把它换成自己文件的命名规律，捕获组对应想要的目录层级，整套逻辑就能直接复用。</p>



<p class="wp-block-paragraph">能识别落地文件并对其做处理之后，可发挥的空间就大了——合并零散笔记、按内容把文档分类、批量把图片缩放到指定尺寸，都只是在这个骨架上多写几行的事。</p>



<p class="wp-block-paragraph">来源：How-To Geek</p>
]]></content:encoded>
					
		
		
			</item>
	</channel>
</rss>
