简体   繁体   中英

file.readlines() returns an empty list despite seek(0)

I am trying to read a file that already exists line by line. I have checked various options on Stackoverflow where they have mentioned to add <file>.seek(0) . This points the code to the beginning of the file. I have added this functionality as well in my code but still, it returns an empty list. Any help would be appreciated.

Thank you!

Tried seek(0) but it does not work.

#!/usr/bin/env python

import subprocess

class ListDirectories:
        def trash_listing(self):
                hdfs_listing_file = open('abc.txt', 'w+')
                subprocess.Popen("hdfs dfs -du -s -h /user/*/.Trash", stdout=hdfs_listing_file, shell=True)
                hdfs_listing_file.close()

tl = ListDirectories()
tl.trash_listing()

class DirectoryFiltering:
        def file_filtering(self):
                with open('abc.txt', 'r') as myfile:
                        myfile.seek(0)
                        lines = myfile.readlines()
                print(myfile)
                print(lines)

df = DirectoryFiltering()
df.file_filtering()

I would expect it to give an output something like:

0 0 /user/abc/.Trash
24 M 72 M /user/def/.Trash

Instead, it gives [] as an output.

You aren't waiting for the program to produce output to the file or exit before attempting to read it.

The function that produces the output to the file should either keep track of the process so it can be waited on or wait on it there. That is the wait call may be delayed until just before the file is needed to be read.

The following waits after closing the opened file. Sure one should use a with open() as here.

class ListDirectories:

        def trash_listing(self):

                hdfs_listing_file = open('abc.txt', 'w+')
                p = subprocess.Popen("hdfs dfs -du -s -h /user/*/.Trash", stdout=hdfs_listing_file, shell=True)
                hdfs_listing_file.close()
                p.wait()

Try this:

def file_filtering(self):
    with open('abc.txt', 'r') as myfile:
        lines = myfile.readlines()
        print(myfile)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM