You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python自定义脚本修改变量值并读取目录最新文本文件

解决方案:自动读取目录中最新创建的文本文件

完全可以实现!我们只需要借助Python的os模块来遍历目录、筛选文本文件并找出最新创建的那个,然后把它的路径动态传给open()函数就好。下面是修改后的完整脚本,我会逐部分解释关键逻辑:

import re
import os

# 定义目标目录(如果脚本和文本文件在同一路径,就用当前工作目录)
target_dir = os.getcwd()

# 筛选目录下所有.txt文件,获取完整路径
txt_files = [os.path.join(target_dir, f) for f in os.listdir(target_dir) 
             if f.endswith('.txt') and os.path.isfile(os.path.join(target_dir, f))]

# 处理没有找到txt文件的情况
if not txt_files:
    print("目录中没有找到文本文件!")
else:
    # 根据文件创建时间排序,取最新的那个(getctime返回创建时间戳,倒序排序后第一个就是最新)
    latest_file = sorted(txt_files, key=lambda x: os.path.getctime(x), reverse=True)[0]
    
    # 用最新文件替换原来的固定文件名
    with open(latest_file, "r") as f:
        for l in f:
            nombre = re.search(r"Nombre:(.*)", l)
            if nombre:
                valor_nombre = nombre.group(1)
                # print(valor_nombre)
            telefono = re.search(r"Telefono:(.*)", l)
            if telefono:
                valor_telefono = telefono.group(1)
                # print(valor_telefono)
            email = re.search(r"Email:(.*)", l)
            if email:
                valor_email = email.group(1)
                # print(valor_email)

关键逻辑说明:

  • os.getcwd():获取当前脚本所在的目录,如果你需要指定其他目录,直接把target_dir改成目标路径即可(比如target_dir = "C:/your/folder/path")。
  • 筛选txt文件:用列表推导式过滤出目录下所有后缀为.txt的文件,同时确保是文件而不是子目录。
  • 排序取最新文件:os.path.getctime()获取文件的创建时间戳,用sorted()倒序排序后,第一个元素就是最新创建的文件。
  • 异常处理:加入了if not txt_files的判断,避免目录中没有txt文件时脚本报错。

如果你的系统是Linux/macOS,有时候getctime会返回文件的最后修改时间而非创建时间,这时候可以改用os.path.getmtime()(最后修改时间),根据你的实际需求调整就行。

内容的提问来源于stack exchange,提问作者Santiago Ruffino

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:12:35