修改文件内容和修改时间

文件管理

  • 查找路径下全部文件全路径
  • 修改文件内容
  • 修改文件创建时间和修改时间
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import time
import os
import re

root_path = '/home/linker-will/Dropbox/_posts'
time_list = []

for root,dirs,files in os.walk(root_path):
for filespath in files:
f_path = os.path.join(root,filespath)
categories = os.path.basename(os.path.dirname(f_path))
f_name = os.path.basename(f_path)[:-3]
mtime = os.path.getmtime(f_path)
ctime = os.path.getctime(f_path)
local_time = time.localtime(os.path.getmtime(f_path))
f_mtime = time.strftime('%Y-%m-%d %H:%M:%S',local_time)

f = open(f_path,'r')
old = f.read()
if categories == '_posts':
print(filespath,"don't have dirname")
pass
if len(re.findall('title:.*\ndate:.*\ncategories:.*',old)) == 0:
print(filespath,"don't have title format")
pass
if len(re.findall('\[TBC\]',old)) != 0:
print(filespath,"[TBC]")

data = re.sub('title:.*\ndate:.*\ncategories:.*',\
'title: %s\ndate: %s\ncategories: %s'%(f_name,f_mtime,categories),old)
f.close()
f = open(f_path,'w')
f.write(data)
f.close()
os.utime(f_path,times=(ctime,mtime))