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.
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)
Advertisement
Answer
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)