python提取文件中含某一字符串的行,并写入新的文件中

with open(r"test.log", encoding='utf-8') as f:  # 从TXT文件中读出数据
    list = []
    for line1 in f:
        if line1 != '\n':  # 去掉空行
            l = line1.split()  # 这句使用空格将文件内容分割成字符段
            list.append(l)  # 将l放入数组
    for item in list:  # 通过一个for循环将某个字符段下含有某个字符串的行显示出来
        if len(item) > 1 and item[1] == 'time': # 提取含time字符串的行,使用这个判断是文件中某些行字符长度仅为一个。
            f = open("time_test.txt", "a")  # 将提取出来的行存入新文件中,"a"为追加的方式存入数据
            f.write(item[6] + "\n")

猜你喜欢

转载自blog.csdn.net/qq_34474071/article/details/123790181