【python实际应用】为文件批量添加内容

为我的自建博客批量添加menu元数据

简述

我在自建的博客中添加了一个当读取到md文件元数据中包含menu项时便会展示的样式,因此对于每个集 下的文件可以批量的添加元数据!
其中利用了tkinter中的 filedialog来进行批量的文件选择,由于python中file的'+'方式在首行添加文件总会遇到诸如乱码之类的问题,因此就放弃了,改为先通过'r'读取内容然后用'w'写入。在写入menu的同时顺道写入了title
其实就是一个简单的文件读写操作啦~

# -*- coding: utf-8 -*-
"""
为我的博客 .md文件添加元数据

@author: dlnb526
"""

from tkinter import *
from tkinter import filedialog
import os.path

class Doc_Title():
    def __init__(self):
        self.root = Tk()
        button_1 = Button(self.root, text="打开文件", command=self.callback).pack()



        mainloop()
    def callback(self):
        self.fileNames = filedialog.askopenfilenames()
        print(self.fileNames)
        self.co_add = input("输入目录节点:")
        for i in self.fileNames:

            self.file_operate(i)


    def file_operate(self,fileName):

        with open(fileName,'r',encoding='UTF-8') as f:
            a = os.path.split(fileName)
            print("您已打开文件:"+a[1])
            dict1 = {};
            b =a[1].split('.')
            print(b[0])
            dict1['title']=b[0]
            dict1['menu']=self.co_add
            print(dict1)
            file_content = f.readlines()
        with open(fileName,'w',encoding='UTF-8') as f:
            f.writelines('---\n')
            for key,value in dict1.items():

                f.writelines(key+': '+value+'\n')
            f.writelines('---\n')
            f.writelines(file_content)
d = Doc_Title()

疑惑

如果有看到的大佬还想请教一下,python中+具体怎么用才能在中文第一行插入东西而后面的内容不乱码~
我原本实现思路如下

def file_operate(self,fileName):
        with open (fileName,'r+',encoding='UTF-8') as f:
            a = os.path.split(fileName)
            print("您已打开文件:"+a[1])
            dict1 = {};
            b=a[1].split('.')
            print(b[0])
            dict1['title']=b[0]
            dict1['menu']=self.co_add
            print(dict1)
            f.seek(0,0)
            f.writelines('---\n')
            for key,value in dict1.items():

                f.writelines(key+': '+value+'\n')
            f.writelines('---\n')
            print(a[1]+'修改成功')

(上面只是思路)
这里直接用了+模式,但是无论怎么样都会乱码(文字内容是中文)。

posted @ 2020-03-23 21:26  柳然  阅读(616)  评论(0编辑  收藏  举报