python在txt文件的每一行增加關鍵字


 原博客遷移到:https://blog.csdn.net/u013171226/article/details/107680310

import os

def updateFile(file,str):
    """
    在文件的每一行前面增加關鍵字
    :param file:文件名
    :param str:關鍵字
    """
    file_data = ""
    with open(file, "r") as f:
        for line in f:
            line = str + line 
            file_data += line
    with open(file,"w") as f:
        f.write(file_data)

base_dir = "./labels"
str  = "head,"
for file_name in os.listdir(base_dir):
    file_name = os.path.join(base_dir, file_name)
    print(file_name)
    updateFile(file_name, str)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM