这里需要 os.path.join(dir, filename) 吗?
我只是做了一堆Python 练习< /a> 并且有一个你应该做的练习。给定目录名,迭代“特殊文件”(包含模式 __\w+__)并输出它们的绝对路径。
这是我的代码:
def get_special_paths(dir):
filenames = os.listdir(dir)
for filename in filenames:
if re.search(r'__\w+__', filename):
print os.path.abspath(os.path.join(dir, filename))
我按照示例中的建议加入了目录和文件名,但我没有看到何时需要 join() 。如果我不加入文件名+目录,而是仅传递文件名,则输出将是相同的。
I'm just doing a bunch of Python exercises and there is an exercise where you should. given a directory name, iterate over the 'special files' (containing the pattern __\w+__) and output their absolute paths.
Here's my code:
def get_special_paths(dir):
filenames = os.listdir(dir)
for filename in filenames:
if re.search(r'__\w+__', filename):
print os.path.abspath(os.path.join(dir, filename))
I joined the dir and filename as suggest in the examples but I don't see while the join() is needed. If I don't join the filename + dir, and instead pass abspath() only the filename, the output would be the same.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅当
dir
等于当前工作目录时,情况不一定如此。要么您需要连接,要么get_special_paths
不应该接受参数,而是假设dir = os.getcwd()
。Only if
dir
equals the current working directory, which is not necessarily the case. Either you need the join, orget_special_paths
should not take an argument, and instead assumedir = os.getcwd()
.