0

I am trying to separate a main file into smaller files based on the presence of a 'file delimiter'. I attempt to use a regex to match this delimiter, serving as the name of the new individual file, and to write out the subsequent lines of the main file to this new file, as follows:

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)

However, I get the following error:

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

Why does it seem that the regex match assignment 'smallerFileName' can not be used outside of the 'if loop'.?

  • Look at this - Should be helpful: \http://stackoverflow.com/questions/2829528/whats-the-scope-of-a-python-variable-declared-in-an-if-statement – Dandy Oct 25 '16 at 03:53

1 Answers1

1

Clearly line == header is not true, hence you never set smallerFileName.

John Zwinck
  • 239,568
  • 38
  • 324
  • 436