eightHundreds
2/5/2017 - 5:51 PM

在当前文件夹下搜素,打开每个py文件,给他们第一行添加字符串

在当前文件夹下搜素,打开每个py文件,给他们第一行添加字符串

# -*- coding: utf-8 -*-
import os
pyfile=set()
dir_queue=set()
dir_queue.add(os.getcwd())
line='# -*- coding: utf-8 -*-'
while len(dir_queue)!=0:
    dir_path=dir_queue.pop()
    print(dir_path)
    for i in os.listdir(dir_path):
        if os.path.isdir(os.path.join(dir_path,i)):
            dir_queue.add(os.path.abspath(os.path.join(dir_path,i)))
        else:
            if i.endswith('.py'):
                pyfile.add(os.path.join(dir_path,i))

for i in pyfile:
    with open(i,'r+',encoding= 'utf8') as f:
        content = f.read()
        if not content.startswith(line):
            f.seek(0, 0)
            f.write(line.rstrip('\r\n') + '\n' + content)