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'.?