为什么此变量未在&if; if语句之外定义'

时间:2016-10-25 03:46:33

标签: python-2.7

我正在尝试根据“文件分隔符”的存在将主文件分成较小的文件。我尝试使用正则表达式来匹配此分隔符,作为新单个文件的名称,并将主文件的后续行写出到此新文件,如下所示:

with open("main_file.txt", 'r') as fhand:
    mainFile = csv.reader(fhand)
    for line in mainFile:
        file_delimeter = "chr[0-9]+"
        header = re.search(pattern, str(line)):
        if line == header:
            smallerFileName = (header.group(0) + ".txt") 
        with open(smallerFileName, 'w') as newFile:
            datawriter = csv.writer(newFile)
            datawriter.writerow(line)

但是,我收到以下错误:

Traceback (most recent call last):
File "sepFiles.py" (...)
    with open(smallerFileName, 'w') as newFile: 
NameError: name 'smallerFileName' is not defined  

为什么正则表达式匹配分配' smallerFileName'不能在&if; if循环之外使用。?

1 个答案:

答案 0 :(得分:1)

显然line == header不正确,因此您从未设置smallerFileName