zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python脚本

Python 脚本
2023-06-13 09:12:01 时间

我的博客即将同步至腾讯云开发者社区,邀请大家一同入驻:https://cloud.tencent.com/developer/support-plan?invite_code=x2aw3y6o6mh7

pip命令

::更新pip命令
python -m pip install --upgrade pip

批量移动文件或者文件夹

这个脚本的主要实现的是一个文件夹中文件的移动和重命名操作,主要借助Python的os库以及shutil库,在平时博客的配置或者资源的迁移中比较经常用到。

import os
from shutil import copy
root_path = ''
target_path = ''
if not(os.path.exists(target_path)):
    os.mkdir(target_path)
# 如果移动的文件夹里有嵌套的文件夹需要使用os.walk()
# 注意该函数的返回参数:当前文件夹名称,子文件夹名称,文件名称
paths=os.listdir(root_path)
i=1
for path in paths:
    # 可根据path.split('.')[-1]获取文件后缀名分开进行操作
    file_path = os.path.join(root_path, path)
    file_copy_path = os.path.join(target_path, str(i)+'.'+path.split('.')[-1])
    #不建议直接在源文件上进行更改,防止意外状况出现
    copy(file_path, file_copy_path)
    i=i+1

文件内容正则替换

import pandas as pd
import re
import os
data = pd.read_excel('目录.xlsx')
for row in data.itertuples():
    title=row.title
    date=row.date
    update=row.updated
    #先读后写的操作实现
    if os.path.exists(f'{title}.md'):
        with open(f'{title}.md', 'r', encoding='utf-8') as f:
            text = f.read()
        with open(f'{title}.md', 'w', encoding='utf-8') as f:
            p1 = r"updated:[ ']*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})[' ]*"
            text = re.sub(p1, 'updated: ' +
                        update.strftime('%Y-%m-%d %H:%M:%S'), text)
            print(text)
            p = r"date:[ ']*(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})[' ]*"
            f.write(re.sub(p, 'date: '+date.strftime('%Y-%m-%d %H:%M:%S'), text))