【发布时间】:2018-01-14 03:11:51
【问题描述】:
我想为 python 提供一个可用于设置输入处理的 Windows“数据路径”。我用谷歌搜索了这个没有运气,现在我想我自己了。
似乎有很多方法可以使用 python 读取文件,在对“\”和“/”以及 windows 路径名感到沮丧之后,我找到了一种方法来设置我的数据路径。这不是一种通用方法,但应该对我有用。
相关问题:这段代码难看吗?这是一种非标准方法吗? 3.6 中有哪些优雅的功能应该使用?
### Title: Process an input file using a 'data path' for a user on windows
import sys
import os
print("OK, starting program...")
file_processed = False
for path, dirs, files in os.walk("/Users/Mike"):
if file_processed: break
for file in files:
if file_processed: break
if file == 'seriousdata.txt':
my_path = os.path.abspath(path)
my_dsn = os.path.join(my_path, file)
print("Opening txt file " + my_dsn + " for input.")
with open(my_dsn) as da_lines:
textlines = (line.rstrip('\r\n') for line in da_lines)
for line in textlines:
print(line)
file_processed = True
if file_processed:
pass
else:
print("File not found")
print("OK, program execution has ended.")
sys.exit() # END SAMPLE CODE SNIPPET
【问题讨论】:
-
是否需要遍历整个目录树才能找到severedata.txt?如果您已经知道文件在哪里,那么将路径指定为命令行参数会简单得多。如果您对此有疑问,请查看this answer。
标签: python python-3.x file-io