Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to have an incomplete block in Python without error?

This is my code which logically throws error that needs indentation:

elif platform == ‘win32’:
IndentationError: expected an indented block

from sys import platform


def test():
    if platform == 'linux':
        with open('$HOME/test.txt', 'r') as file:
    elif platform == 'win32':
        with open(r'%userprofile%\\test.txt', 'r') as file:

            for line in file:
                print(line)

I need Python to check if OS is whether Linux or Windows, open the file in home of that user and do the same code (in this case for loop) after detecting the OS.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Is there a way to avoid the following way so that I won’t have repeated code?

from sys import platform


def test():
    if platform == 'linux':
        with open('$HOME/test.txt', 'r') as file:
            for line in file:
                print(line)
    elif platform == 'win32':
        with open(r'%userprofile%\\', 'r') as file:
            for line in file:
                print(line)

>Solution :

Consider assigning a string in a judgment statement:

def test():
    if platform == 'linux':
        filename = '$HOME/test.txt'
    elif platform == 'win32':
        filename = r'%userprofile%\\test.txt'
    else:
        ...

    with open(filename, 'r') as file:
        for line in file:
            print(line)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading