Skip to content

Latest commit

 

History

History
243 lines (171 loc) · 5.61 KB

File metadata and controls

243 lines (171 loc) · 5.61 KB
Error in user YAML: (<unknown>): found a tab character that violate indentation while scanning a plain scalar at line 3 column 3
---
- oeasy Python 0457
- 这是 oeasy 系统化 Python 教程,从基础一步步讲,扎实、完整、不跳步。愿意花时间学,就能真正学会。
- 本教程同步发布在: 
	- 个人网站: `https://oeasy.org` 
	- 蓝桥云课: `https://www.lanqiao.cn/courses/3584` 
	- GitHub: `https://github.com/overmind1980/oeasy-python-tutorial` 
	- Gitee: `https://gitee.com/overmind1980/oeasypython` 
---

二重循环

回忆

  • 上次我们把容器序列化了
    • 并且存储在文件当中
    • 这些容器是重要的数据结构

图片描述

  • 打开文件之后
    • 得到了f
  • 这f 是 什么类型的 变量 呢?🤔

基础准备

echo "木,火,土,金,水" >> wuxing.txt
echo "青,赤,黄,白,黑" >> wuxing.txt
echo "东,南,中,西,北" >> wuxing.txt
echo "肝,心,脾,肺,肾" >> wuxing.txt
echo "生,长,化,收,藏" >> wuxing.txt
cat wuxing.txt
  • 先准备这样一个wuxing.txt文件

图片描述

  • 我们是怎么得到文件的呢?

定义

  • 进入游乐场
python3
  • 我们首先读一个文件
with open("wuxing.txt", "rt") as f:
	print(type(f))
  • 然后看看
    • 这个文件具体是什么 type 的

图片描述

  • 什么是 TextIOWrapper 呢?

TextIOWrapper

图片描述

  • 查看帮助

图片描述

  • 继续往后翻

iter 方法

  • 我找到了这个

图片描述

  • 这说明 TextIOWrapper 是一个可迭代的对象
    • 可以用 for 来遍历他

遍历

with open("wuxing.txt","rt") as f:
    for line in f:
        print(line)
  • 遍历很好用

图片描述

  • 我们可以给他加一个编号么?

编号

with open("wuxing.txt","rt") as f:
    for line in enumerate(f):
        print(line)
  • enumerate
    • 给 可迭代变量 缝合个编号

图片描述

  • 我可以把
    • 纵向的列
    • 缝合到一起么?

准备缝合 zip

lst = []
with open("wuxing.txt","rt") as f:
    for line in f:
		lst.append(line.replace("\n", "").split(","))	 
        print(line)
print(lst)
  • 首先 把文件 制作为 二位数组
    • 然后 想办法 缝合 同一位置的 元素

图片描述

  • 其实是 矩阵转置
    • matrix transposition

缝合 zip

lst = []
with open("wuxing.txt","rt") as f:
    for line in f:
		lst.append(line.replace("\n", "").split(","))	 
        print(line)
print(lst)
z = zip(l[0], l[1], l[2], l[3], l[4])
for row in z:
	print(row)
  • 这样同声相应 同气相求

图片描述

  • 同样类型的东西就映射到一起了

阴阳应象大论篇第五

图片描述

需求

图片描述

import os
import shutil
import exifread
from datetime import datetime
from pathlib import Path


def get_capture_date(file_path):
    """严格模式:仅使用EXIF日期,不自动回退到修改时间"""
    try:
        with open(file_path, 'rb') as f:
            tags = exifread.process_file(f, stop_tag='DateTimeOriginal')
            if 'EXIF DateTimeOriginal' in tags:
                date_str = str(tags['EXIF DateTimeOriginal'])
                return datetime.strptime(date_str, '%Y:%m:%d %H:%M:%S')
    except Exception as e:
        print(f"EXIF读取失败 {file_path}: {str(e)}")
    return None  # 严格模式不自动使用修改时间


def organize_photos(source_dir, output_base):
    """整理照片主函数(新增无日期分类)"""
    image_exts = {'.jpg', '.jpeg', '.png', '.cr2', '.nef', '.dng'}

    for file_path in Path(source_dir).rglob('*'):
        if file_path.suffix.lower() not in image_exts:
            continue

        try:
            # 获取拍摄日期
            capture_date = get_capture_date(file_path)

            # 确定目标路径
            if capture_date:  # 有EXIF日期的情况
                date_folder = capture_date.strftime("%Y/%m/%d")
                dest_dir = Path(output_base) / date_folder
            else:  # 无日期信息的情况
                dest_dir = Path(output_base) / "无日期信息"

            # 创建目录并处理重名
            dest_dir.mkdir(parents=True, exist_ok=True)
            dest_path = dest_dir / file_path.name
            counter = 1
            while dest_path.exists():
                dest_path = dest_dir / f"{file_path.stem}_{counter}{file_path.suffix}"
                counter += 1

            # 移动文件
            shutil.move(str(file_path), str(dest_path))
            status = "无日期" if not capture_date else capture_date.strftime("%Y-%m-%d")
            print(f"Moved [{status}]: {file_path.name}")

        except Exception as e:
            print(f"处理失败 {file_path.name}: {str(e)}")


if __name__ == "__main__":
    sd_card_path = "/media/your_sd_card"
    output_directory = "/photo_collection"

    organize_photos(sd_card_path, output_directory)


总结

  • 本章节 研究了 文件流对象的 遍历
    • 文件流 本质 是iterable 的对象
      • 可以是 文本流
      • 也可以是字节流
    • 还可以遍历 整个文件

图片描述

  • 关于 文本处理 还有什么说法吗?🤔
  • 下次再说 👋

  • 本文来自 oeasy Python 系统教程。
  • 想完整、扎实学 Python,
  • 搜索 oeasy 即可。