【问题标题】:Python 'if...continue' unexpectedly returns control to parent loop of current loopPython 'if...continue' 意外地将控制权返回给当前循环的父循环
【发布时间】:2017-03-30 20:42:29
【问题描述】:

我在 Visual Studio 中使用 Python,在调试模式下单步执行代码。检查第一个if..continue 语句后,控制权返回for file..,正如我所料。

但是,在第二次通过时,当它下降到下一个 if..continue 语句时,控制返回到父 for dir 循环的开始,而我预计它会再次返回到 for file..。目标是忽略名称为_*.csv 的任何子目录和 csv 文件(我希望我现在不必深入学习其他模式匹配的东西——如果可能的话,需要处理当前的小任务):

for dir in os.listdir(masterDirPath):    
    currentDir = masterDirPath + dir

    # iterate through csv logs within current data folder, aggregating data
    for file in os.listdir(currentDir):

        path = os.path.join(currentDir, file)
        if os.path.isdir(path):
            # skip directories
            continue

        if file.startswith('_'):
            # skip custom files
            continue

        if file.endswith(".csv"):
            # open log file
            .
            .
            .

【问题讨论】:

  • 也许您已经遍历了该目录中的所有文件?
  • @Moberg - 嗨,谢谢你的回答,但是,不,我检查并仔细检查了我正在查看我的测试文件夹,该文件夹有意包含一个子目录,一个有效的“csv”是检查和一个名为“_testMe.csv”的 csv。你是说,据你所知,它应该按我的预期工作吗?
  • 在循环开头添加print "-{}-".format(file)。也许您的操作系统在文件名之前/之后添加了一些空格。如果是这样你可以试试file = file.strip()

标签: python file csv filenames matching


【解决方案1】:

据我了解,您在 os.listdir 中有一个目录列表以及每个目录中的文件列表。

理想情况下,您应该将一个目录加载到 currentDir --> 这个目录应该遍历每个文件。

我相信控制流会受到影响,因为您将相同的 currentDir 分配给所有目录。

试试这个:

for dir in os.listdir(masterDirPath):    
    currentDir = masterDirPath + dir

  # iterate through csv logs within current data folder, aggregating data
  ##### indent this part of your code #####

     for file in os.listdir(currentDir):
        path = os.path.join(currentDir, file)

        if os.path.isdir(path):
           # skip directories
           continue

        if file.startswith('_'):
           # skip custom files
           continue

        if file.endswith(".csv"):
          # open log file
          .
          .
          .

【讨论】:

  • 谢谢 - 我猜这是一个缩进错误 - 我复制并粘贴了你的版本,现在它似乎工作正常。
猜你喜欢
  • 1970-01-01
  • 2019-07-31
  • 2014-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-09
相关资源
最近更新 更多