[英]Python: How do I return the parent directory name of each file os.walk returns?
[英]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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.