Python- 如何查看 os.walk 文件内容而不每次打印文件路径?

Python- How can I view os.walk file contents without printing the file paths each time?

我使用此脚本递归地遍历目录并查看文件内容。但是,当我输入文件内容时,它会显示在顶部并再次打印整个文件列表。我只希望文件路径列表打印一次,然后用户可以打开任意数量的文件,而无需每次都打印列表。希望这是有道理的。

import os
while True:
    for root, dirs, files in os.walk("/home"):
        for file in files:
            print(os.path.join(root, file))     
    fname = raw_input('Enter filepath to view '
                    '(leave empty to proceed without viewing another file):')

    if not fname:
        break

    f = open(fname, 'r')
    print f.read()

在 while 循环之外打印目录树:

import os

for root, dirs, files in os.walk("/home"):
    for file in files:
        print(os.path.join(root, file))     

while True:
    fpath = raw_input('Enter filepath to view '
                    '(leave empty to proceed without viewing another file):')

    if not fpath:
        break

    with open(fpath, 'r') as f:
        print f.read()