python - 在第一行插入字符串使用python3
问题描述
我要插入
# -*- coding: utf-8 -*-
当我使用 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
解决方案
# -*- coding: utf-8 -*-
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+",encoding='UTF-8') as f:
if item.endswith(".py"):
s = f.read(); f.seek(0); f.write("# -*- coding: utf-8 -*-\n" + s)
else:
print('other:' + item)
target_folder = 'F:\\project\\test'
show_folder_content(target_folder)
推荐阅读
- django - TypeError:kitty() 得到了一个意外的关键字参数“startdate”
- django - 防止 Redis/Celery 计划任务被多次处理 - Heroku 上的 Django
- java - 您可以重新平衡未知大小的不平衡拆分器吗?
- javascript - cesiumWorkerBootstrapper 使用 RequireJS importScripts 时出错
- c# - 如何将 CSV 文件拆分为多个部分
- javascript - 如何在 JavaScript 函数中使用 php
- bash - 如何删除外壳中标准输入行上的美元符号头?
- php - POST http://localhost/website/wp-admin/admin-ajax.php 400(错误请求)
- ios - Xcode 10.3 其他 iOS 版本模拟器在哪里
- javascript - 切换没有状态的 React 复选框