【问题标题】:Loop through files but skip subdirectories遍历文件但跳过子目录
【发布时间】:2020-05-19 11:51:59
【问题描述】:

我想遍历目录中的文件(我很容易做到这一点)但跳过子目录中的文件(我不明白这个工作)。

我将如何实现这一目标?目前我使用这个:

for subdir, dirs, files in os.walk(scriptdir1):
    for file in files:
        if os.path.isfile(scriptdir + file):
            with open(file, "rb") as f:
                dbx.files_upload(f.read(), "/" + file, mode=dropbox.files.WriteMode.overwrite)

这就是我的文件夹的样子(这可能会改变,所以我不想要任何特定于文件夹的答案):

所以我想遍历这个目录中的文件,并跳过子目录中的文件。我只想要 THIS 目录中的文件。

谢谢

【问题讨论】:

  • 你为什么要os.path.isfile??? os.walk 将在其第三个输出中返回 only 个文件。如果您不想进入子目录,为什么要使用os.walk?使用os.listdir+os.path.isfile
  • 这能回答你的问题吗? List files ONLY in the current directory
  • 谢谢@Greg,我不知道为什么我找不到这个。我实际上搜索了一个小时..也谢谢Bakuriu,我会评论这个作为答案。

标签: python python-3.x windows loops file


【解决方案1】:

你可以在这里使用glob:-

import glob
file = glob.glob(scriptdir1 + "/*/*")
 with open(file, "rb") as f: dbx.files_upload(f.read(), "/"+file,mode=dropbox.files.WriteMode.overwrite)

您还可以在* 的位置编写正则表达式来匹配某些特定文件。

【讨论】:

    【解决方案2】:

    我用它来让它工作:

    files = [f for f in os.listdir('.') if os.path.isfile(f)]
    for f in files:
        with open(f, "rb") as fi:
            dbx.files_upload(fi.read(), "/" + f, mode=dropbox.files.WriteMode.overwrite)
            print("Uploaded: " + f)
    

    感谢 Greg 和 Bakuriu 指出正确答案

    【讨论】:

      猜你喜欢
      • 2012-08-22
      • 1970-01-01
      • 2021-07-09
      • 1970-01-01
      • 1970-01-01
      • 2017-09-10
      • 1970-01-01
      • 2016-01-22
      • 1970-01-01
      相关资源
      最近更新 更多