我有几个在嵌套循环中递归调用的函数。我的计划的最终目标是:
a)每年循环,
b)每年每年,每个月循环(共12个),
c)每个月内,循环每天(使用自生成的日程表),
d)并读取2个文件并将它们合并到另一个文件中。
在每个实例中,只有存在时才会进入目录。否则,我只是跳过它去下一个。当所有文件存在时,我的代码做得非常好,但是当缺少其中一个文件时,我只想简单地跳过创建合并文件的整个过程并继续循环。我得到的问题是语法错误,指出continue
在循环中没有正确。我只在函数定义中得到这个错误,而不是在它们之外。
有人可以解释为什么我会收到此错误吗?
import os, calendar
file01 = 'myfile1.txt'
file02 = 'myfile2.txt'
output = 'mybigfile.txt'
def main():
#ROOT DIRECTORY
top_path = r'C:\directory'
processTop(top_path)
def processTop(path):
year_list = ['2013', '2014', '2015']
for year in year_list:
year_path = os.path.join(path, year)
if not os.path.isdir(year_path):
continue
else:
for month in range(1, 13):
month_path = os.path.join(year_path, month)
if not os.path.isdir(month_path):
continue
else:
numDaysInMth = calendar.monthrange(int(year), month)[1]
for day in range(1, numDaysInMth+1):
processDay(day, month_path)
print('Done!')
def processDay(day, path):
day_path = os.path.join(path, day)
if not os.path.isdir(day_path):
continue
else:
createDailyFile(day_path, output)
def createDailyFile(path, dailyFile):
data01 = openFile(file01, path)
data02 = openFile(file02, path)
if len(data01) == 0 or len(data02) == 0:
# either file is missing
continue
else:
# merge the two datalists into a single list
# create a file with the merged list
pass
def openFile(filename, path):
# return a list of contents of filename
# returns an empty list if file is missing
pass
if __name__ == "__main__": main()
答案 0 :(得分:1)
您可能在processDay
和createDailyFile
收到了该错误,对吗?这是因为这些函数中没有循环,但您使用continue
。我建议在其中使用return
或pass
。
答案 1 :(得分:1)
continue
语句仅适用于循环,因为错误消息暗示如果您的函数是按结果显示的,那么您可以使用pass
。
答案 2 :(得分:1)
continue只能出现在循环中,因为它告诉python不执行下面的行并转到下一次迭代。因此,此处的语法无效:
def processDay(day, path):
day_path = os.path.join(path, day)
if not os.path.isdir(day_path):
continue # <============ this continue is not inside a loop !
else:
createDailyFile(day_path, output)enter code here
您的createDailyFile函数也是如此。
您可能希望将其替换为退货?
答案 3 :(得分:1)
你只能在循环中明确地使用continue
(否则,你首先要保证在循环中调用该函数?)如果需要堆栈展开,请考虑使用异常({{3 }})。
我认为你可以让你的函数返回一个值,表明操作是否成功完成:
def processDay(day, path):
do_some_job()
if should_continue:
return False
return True
然后在你的主要代码中简单地说
if not processDay(day, path):
continue