Search code examples
pythonziptemporary-files

how do I write lines to a NamedTemporaryFile then print each line


I'm trying to unzip a zip file containing a csv file and write all the rows from the csv file into a NamedTemporaryFile. Then print the lines from the temp file to ensure that it has written the desired lines properly. This is my current code which when the "print(line)" is called returns a blank.

with zipfile.ZipFile(file_name) as zip_fp:
        for item in zip_fp.namelist():
            temp_file = NamedTemporaryFile()
            with zip_fp.open(item) as fp:
                with open(temp_file.name, mode='wb+') as temp_fp:
                    temp_fp.writelines(fp.readlines())
                    for line in temp_fp:
                        print(line)

Please help.


Solution

  • That's because temp_fp.writelines(fp.readlines()) has written all the lines to the file and the cursor is now at the end of file so you wont get anything. Try out the below code (last 3 lines are added to your code):

    with zipfile.ZipFile(file_name) as zip_fp:
            for item in zip_fp.namelist():
                temp_file = NamedTemporaryFile()
                with zip_fp.open(item) as fp:
                    with open(temp_file.name, mode='wb+') as temp_fp:
                        temp_fp.writelines(fp.readlines())
                    with open(temp_file.name, mode='r') as temp_fp:
                        for line in temp_fp:
                            print (line)
                    
    

    OR - seek to the start of file and read all the line:

    with zipfile.ZipFile(file_name) as zip_fp:
            for item in zip_fp.namelist():
                temp_file = NamedTemporaryFile()
                with zip_fp.open(item) as fp:
                    with open(temp_file.name, mode='wb+') as temp_fp:
                        temp_fp.writelines(fp.readlines())
                        # SEEK TO START OF FILE
                        temp_fp.seek(0,0)
                        for line in temp_fp:
                            print (line)