python用数字替换值字符串

时间:2017-06-21 11:50:31

标签: python

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

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个文件...等等

0 个答案:

没有答案