如何在 Python 中有一个不完整的块而不会出错?

How to have an incomplete block in Python without error?

这是我的代码,逻辑上会抛出需要缩进的错误:

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)

我需要Python检查OS是Linux还是Windows,打开那个用户家里的文件,做同样的代码(在这个case for loop) 在检测到 OS.

之后

有没有办法避免下面这种方式,让我不会出现重复代码?

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)

考虑在判断语句中赋值字符串:

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)