我要插入
# -*- coding: utf-8 -*-
到多路径(包括子目录和diff目录)中多文件的第一行当我使用open + whrite python代码时,结果将追加到底部
import os
def show_folder_content(folder_path):
folder_content = os.listdir(folder_path)
for item in folder_content:
if os.path.isdir(folder_path + '\\' + item):
print('folder:' + item)
show_folder_content(folder_path + '\\' + item)
elif os.path.isfile(folder_path + '\\' + item):
print('file:' + item)
f = open(folder_path + '\\' + item, "a")
f.write("\n# -*- coding: utf-8 -*-")
f.close()
else:
print('other:' + item)
target_folder = 'F:\\project\\test_source'
show_folder_content(target_folder)
如何附加所有文件的顶部(第一行),原因是'我想洗澡使我的代码支持utf8
import os
def show_folder_content(folder_path):
folder_content = os.listdir(folder_path)
for item in folder_content:
if os.path.isdir(folder_path + '\\' + item):
print('folder:' + item)
show_folder_content(folder_path + '\\' + item)
elif os.path.isfile(folder_path + '\\' + item):
print('file:' + item)
with open(folder_path + '\\' + item, "r+") as f:
s = f.read(); f.seek(0); f.write("# -*- coding: utf-8 -*-\n" + s)
# f = open(folder_path + '\\' + item, "a")
# f.write("\n# -*- coding: utf-8 -*-")
# f.close()
else:
print('other:' + item)
target_folder = 'F:\\project\\test_source'
show_folder_content(target_folder)