创建一个函数来检查是否存在文件以及文件是否正确

时间:2017-02-03 14:02:14

标签: python

我正在尝试检查是否存在某些文件。如果它们存在,我想检查它们是否正确。要做到这一点,我做了一个功能,但它不起作用。这就是我一直在尝试的。有什么帮助吗?

def check_file(namefile):
    if not os.path.isfile(namefile):
        return False
else:
    extension=namefile.split(".")[-1]
    if extension=="txt":
      #in this case correct means it finds "END" in the file  
        if "END" in open("*.txt").read(): 
            print "file %s already exists"%(namefile)

2 个答案:

答案 0 :(得分:0)

以下是您的代码的更正版本。它将打开文件并检查文件中是否有“END”。

{{1}}

答案 1 :(得分:0)

我建议使用适当的 CLEAR / init temporary/result variables to zero STORE q_flag STORE r_flag STORE RESULT SUBT X / try (-Dividend) value SKIPCOND 800 JUMP DividendWasPositive / positive or zero STORE X / (-Dividend) positive, rewrite original X STORE q_flag / set flags to positive value (X) STORE r_flag DividendWasPositive, CLEAR SUBT Y / try (-divisor) value SKIPCOND 400 JUMP DivisorNotZero HALT / division by zero detected, error DivisorNotZero, SKIPCOND 800 JUMP DivisorWasPositive STORE Y / (-divisor) positive, rewrite original Y / flip quotient flag value (zero <-> nonzero) ("nonzero" == X) LOAD X / will not "flip" anything when 0 == X SUBT q_flag / but then q = 0, so it's harmless deficiency STORE q_flag / q_flag is now zero or positive (X) value DivisorWasPositive, / here X and Y contain absolute value of input numbers / q_flag is positive value when quotient has to be negated / r_flag is positive value when remainder has to be negated / .. do your division here .. / patching results by the q/r flags from the prologue part AdjustQuotientSign, LOAD q_flag SKIPCOND 800 JUMP AdjustRemainderSign CLEAR SUBT RESULT STORE RESULT / quotient = -quotient AdjustRemainderSign, LOAD r_flag SKIPCOND 800 JUMP SignsAdjusted CLEAR SUBT REMAIN STORE REMAIN / remainder = -remainder SignsAdjusted, HALT q_flag, DEC 0 r_flag, DEC 0 ... rest of your variables 函数并重新组织逻辑:

os.path

from os.path import exists, splitext def check_file(namefile): if exists(namefile) and splitext(namefile)[-1] == "txt": with open(namefile) as fobj: for line in fobj: if "END" in line: return True return False 将分机拆开,os.path.splitext检查文件是否存在。最好使用os.path.exists打开文件进行自动关闭。对于较大的文件,使用with open()逐行阅读并在找到for line in fobj:后立即返回True也会更有效。如果您已找到END,则可以避免阅读以下所有行。