File.readlines() not returning any strings; possible file not opening

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error File.readlines() not returning any strings; possible file not opening on this date .

I’m working on building a script for configuring disks automatically on linux systems. One of my functions is not working and for the life of me I cannot figure out why.

I’ve tested the code on pythontutor.com with no errors. When I run the code on my machine, I get no errors, but instead of the function returning data from the file “disks.txt” I get empty dictionaries.

I have tried to add print statements at different points in the process to see what is going on, but nothing prints.

Here is my function:

def check_for_disks():
    cmd = 'lsblk -l -o name,mountpoint'.split()
    driveDict = {}
    finalDict = {}
    diskFile = open("disks.txt", "w+")
    subprocess.Popen(cmd, stdout=diskFile)
    diskFile.close()
    diskFile = open("disks.txt", "r+")
    for line in diskFile.readlines():
        dictItem = line.split()
        try:
            driveDict[dictItem[0]] = dictItem[1]
        except(IndexError):
            driveDict[dictItem[0]] = "No MountPoint Defined"
    diskFile.close()
    for k, v in driveDict.items():
        if 'sd' in k:
            finalDict[k] = v
        else:
            pass
    return finalDict

This part works flawlessly and creates the file I want, with the relevant information:

def check_for_disks():
    cmd = 'lsblk -l -o name,mountpoint'.split()
    driveDict = {}
    finalDict = {}
    diskFile = open("disks.txt", "w+")
    subprocess.Popen(cmd, stdout=diskFile)
    diskFile.close()

This part fails:

diskFile = open("disks.txt", "r+")
for line in diskFile.readlines():

It is seemingly just not opening the file. I’ve checked the file with ls -la and seen its permissions are fine aka -rw-rw-r–

I’ve tried with open(“disks.txt”, “a+”) as diskFile:

I’ve tried the options “r”, “r+”, “a+”

I’ve run the script sudo

Any help is appreciated

PLEASE SAVE ME I’M GOING NUTS

Answer

TLDR: the file is empty when you open it.

The following command opens a new thread, and the new thread, starts to write this file.

subprocess.Popen(cmd, stdout=diskFile)

But at the same time, as the file is begin created you start to read the file. Two threads makes this command faster, but I don’t think you need that. Simply, wait until the file is finished before reading it.

something like this, should do what you want

p = subprocess.Popen(cmd, stdout=diskFile)
p_status = p.wait() #finish writing the file before starting to read it

Let me know if you really need to multiple threads, or if this snippet has any issues.