我在使用if语句时遇到语法错误。它是用一个不同的版本正常工作,但我写的输出日志,我不喜欢它如何会为它检查每个文件的输出,我一次,如果该文件存在,或不希望只写。
下面的第一个代码不起作用,它表示第三个文件是未定义的变量(代码的第五行)。
第二个代码块是它之前的工作方式。
有人知道该如何构造吗?
if any(file.endswith('.ppt') for file in os.listdir(scanDestinationPath)):
os.startfile(machineFolderDir + machineType + '\\' +
partNumber + ' REV ' + revisionNumber + '\\' +
file, 'print')
errorLog = open(logBookDir + 'log.txt', 'a+')
errorLog.write('\nA setup sheet called PROG' + programNumber +
' ' + partNumber + ' ' + revisionNumber +
'.ppt was printed.\n')
errorLog.close()
else:
errorLog = open(logBookDir + 'log.txt', 'a+')
m = ('The exception occurred in printDecoSetupSheet().There does not appear '
f'to be a .ppt setup sheet file in folder {partNumber} {revisionNumber} '
f'under {machineType}. Moving on...\n')
errorLog.write(m)
errorLog.close()
第二个代码块:
if file.endswith(".ppt"):
os.startfile(machineFolderDir + machineType + '\\' +
partNumber + ' REV ' + revisionNumber + '\\' +
file, 'print')
errorLog = open(logBookDir + 'log.txt', 'a+')
errorLog.write('\nA setup sheet called PROG' + programNumber +
' ' + partNumber + ' ' + revisionNumber +
'.ppt was printed.\n')
errorLog.close()
else:
errorLog = open(logBookDir + 'log.txt', 'a+')
m = ('The exception occurred in printDecoSetupSheet().There does not appear '
f'to be a .ppt setup sheet file in folder {partNumber} {revisionNumber} '
f'under {machineType}. Moving on...\n')
errorLog.write(m)
errorLog.close()
回溯是:
Exception has occurred: NameError name 'file' is not defined File "C:\Users\MacalusoC\Desktop\Technical Docs\TLC_Program_Release\Scripts\Program_Release_v4.py", line 348, in printDecoSetupSheet file, 'print') File "C:\Users\MacalusoC\Desktop\Technical Docs\TLC_Program_Release\Scripts\Program_Release_v4.py", line 835, in main printDecoSetupSheet(scanDestinationPath) File "C:\Users\MacalusoC\Desktop\Technical Docs\TLC_Program_Release\Scripts\Program_Release_v4.py", line 869, in <module> main()