вставить строку в первой строке использовать python3 - PullRequest
0 голосов
/ 06 февраля 2020

Я хочу вставить

# -*- 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)

как добавить начало всех файлов (первая строка), потому что я хочу, чтобы bath заставил мой код поддерживать utf8

1 Ответ

0 голосов
/ 06 февраля 2020
# -*- 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)
...