python将值字符串替换为numb

2024-09-27 07:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在建立一个系统,对一些.txt格式的.log文件进行排序,以便以后可以将其发送到excel。有70多个文件,在每一个文件im扫描关键字,我得到1000+字符串,我想保存在一个.txt。我可以得到我想要的每个字符串,并查看每个日志从哪个.log文件中获取,但是现在我想用相应的数字1,2,3,4,5…(每个文件一个数字,而不是它的文件名)重命名.log来自的文件。代码:

import glob


def LogFile(filename, tester):
    message = []
    data = []
    print(filename)

    with open(filename) as filesearch:   # open search file
        filesearch = filesearch.readlines()   # read file

    i = 1
    d = {}
    for filename in filename:
        if not d.get(filename, False):
            d[filename] = i
            i += 1

    for line in filesearch:
        if tester in line:   # extract ""
            start = '-> '
            end = ':\ '
            number = line[line.find(start)+3: line.find(end)]        #[ord('-> '):ord(' :\ ')]
            data.append(number)   # store all found wors in array
            text = line[line.find(end)+3:]
            message.append(text)

    with open('Msg.txt', 'a') as handler:  # create .txt file
        for i in range(len(data)):
            handler.write(f"{i}|{data[i]}|{message[i]}")

# open with 'w' to "reset" the file.
with open('Msg.txt', 'w') as file_handler:
    pass
# ---------------------------------------------------------------------------------


for filename in glob.glob(r'C:\Users\FKAISER\Desktop\AccessSPA\SPA\*.log'):
    LogFile(filename, 'Sending Request: Tester')

我试过使用这个函数

i = 1
d = {}
for filename in filename:
    if not d.get(filename, False):
        d[filename] = i
        i += 1

但看起来是这样的

enter image description here

我希望每个文件有相同的数字,在图片中,1表示所有26个日志和2表示该文件夹中的10个文件。。。等等


Tags: 文件intxtlogmessagefordatawith

热门问题