Created
June 9, 2022 12:05
-
-
Save fishyer/26544032678f0fe7f8533a1a13d5d087 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
import os | |
from this import d | |
def converDataFormat(text): # 日期格式转换 2012-09-20 -> 2012_09_20 | |
srcTime = datetime.strptime(text, '%Y-%m-%d') | |
destTime = srcTime.strftime("%Y_%m_%d") | |
return destTime | |
def printPath(path): # 打印文件路径 | |
print(path) | |
print(os.path.dirname(path), ".dir") | |
print(os.path.basename(path), ".basename") | |
print(os.path.splitext(path)[0], ".stem") | |
print(os.path.splitext(path)[1], ".suffix") | |
print(os.path.splitext(os.path.basename(path))[0]) | |
def traverseDir(dir): # 遍历文件夹 | |
files = os.listdir(dir) | |
for file in files: | |
if not os.path.isdir(file): | |
f = open(f"{dir}/{file}") | |
name = os.path.splitext(os.path.basename(file))[0] | |
print(name) | |
def readFile(file): # 遍历文件,一行行遍历,读取文本 | |
str = "" | |
iter_f = iter(file) | |
for line in iter_f: | |
str = str + line | |
return str | |
def traverseDirWithProcess(dir, process): # 遍历文件夹,对每个文件都做一种操作 | |
files = os.listdir(dir) | |
for file in files: | |
if not os.path.isdir(file): | |
f = f"{dir}/{file}" | |
process(f) | |
# journals/2022-04-01.md -> journals/2022_04_01.md,没办法,为了兼容Logseq的日志格式 | |
def renameFileByDate(path): | |
name = os.path.splitext(os.path.basename(path))[0] | |
dir = os.path.dirname(path) | |
suffix = os.path.splitext(path)[1] | |
if "-" in name: | |
dest = converDataFormat(name) | |
print(f"{dir}/{name}{suffix}", "->", f"{dir}/{dest}{suffix}") | |
os.rename(f"{dir}/{name}{suffix}", f"{dir}/{dest}{suffix}") | |
dir = "C:/Users/Administrator/Dropbox/MyObsidian/MyHulu/journals" | |
text = '2012_09_20' | |
traverseDirWithProcess(dir, renameFileByDate) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment