这里需要 os.path.join(dir, filename) 吗?

发布于 2024-09-27 18:50:08 字数 506 浏览 0 评论 0原文

我只是做了一堆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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏の忆 2024-10-04 18:50:08

如果我不加入文件名+目录,而是仅传递文件名到abspath(),则输出将是相同的。

仅当 dir 等于当前工作目录时,情况不一定如此。要么您需要连接,要么 get_special_paths 不应该接受参数,而是假设 dir = os.getcwd()

If I don't join the filename + dir, and instead pass abspath() only the filename, the output would be the same.

Only if dir equals the current working directory, which is not necessarily the case. Either you need the join, or get_special_paths should not take an argument, and instead assume dir = os.getcwd().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文