Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中读取压缩文件并将其写入另一个文件?_Python_File_Zip_Filesystems_Writing - Fatal编程技术网

如何在Python中读取压缩文件并将其写入另一个文件?

如何在Python中读取压缩文件并将其写入另一个文件?,python,file,zip,filesystems,writing,Python,File,Zip,Filesystems,Writing,我有多个拉链都包含一个文件。这些ZIP中的文件是csv文件,包含分配的记录。这是文件外观的一个示例: 2020-01-01-14:00:00,TM1,TM2,TM3,TM4,TM5,Name2,Name5,Name6,Name7 2020-01-01-14:00:00,TM1,TM2,TM3,TM4,TM5,Name2,Name5 2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5, Name1,Name2,Name3,Name4,Name5,Name6 2020-0

我有多个拉链都包含一个文件。这些ZIP中的文件是csv文件,包含分配的记录。这是文件外观的一个示例:

2020-01-01-14:00:00,TM1,TM2,TM3,TM4,TM5,Name2,Name5,Name6,Name7
2020-01-01-14:00:00,TM1,TM2,TM3,TM4,TM5,Name2,Name5
2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5, Name1,Name2,Name3,Name4,Name5,Name6
2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5,Name2,Name3,Name4,Name5,Name6
2020-01-01-14:00:00,TM1,TM2,TM3,TM4,TM5,Name2,Name5
2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5,Name2,Name3,Name4,Name5,Name6,Name7
我试图在zip中读取这些文件(不提取它们),并根据某些条件将每个文件的行写入一个新文件

这就是条件。只有当这两个条件都为真时,我才会将该行读入一个新文件

  • 行必须至少包含以下单词之一('Name1、Name2、Name3')
  • 行中的第五个单词必须是“年龄”
  • 这是我的代码:

    import zipfile
    import os
    import pandas as pd
    import csv
    
    root = r'c:\data\FF\Desktop\archive\archive.zip'
    destination = r'c:\data\FF\Desktop\archive'
    
    with zipfile.ZipFile(root, 'r') as my_zip:
        my_zip.extractall(destination)   #<----unzipping the file because I dont know how to read it directly :(
       
     
    search_age = 'AGE'   
    search_names = ['Name1','Name2', 'Name3']
     
    for file in os.listdir(destination):
        if file.endswith('.txt'):   #<--- reading the unzipped file only.
            with open(file, 'r') as my_file:
                reader = csv.reader(my_file)
                for row in reader:
                    if search_age == row[4] and x for x in search_names in row: #<-- check for AGE and for 'Name1, Name2 or Name3'
                        with open('new_file.txt', 'w') as new_file:
                            for row in reader:
                                new_file.write(row) #<--- write the found lines to a new file.
                        
    
    谁能告诉我怎么解决这个问题?多谢各位

    2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5, Name1,Name2,Name3,Name4,Name5,Name6
    2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5,Name2,Name3,Name4,Name5,Name6
    2020-01-01-14:00:00,TM1,TM2,TM3,AGE,TM5,Name2,Name3,Name4,Name5,Name6,Name7