import os
target_dir = "xxx.xxx.xx.xx/path/to/file/dir"
start_seq = "*** Start Sequence ***"
end_seq = "*** End Sequence ***"
def tp_parser(file):
with open(file) as in_f:
lines = in_f.readlines()
f_name = in_f.name[12:16]
for i, line in enumerate(lines):
if line.startswith(start_seq):
start_line = i
elif line.startswith(end_seq):
end_line = i
with open("{0}_Target_Map.txt".format(f_name), "w") as out_f:
for i, line in enumerate(lines):
if start_line <= i < end_line:
print(line)
# out_f.write(line)
for file in os.listdir(os.chdir(target_dir)):
tp_parser(file)
I wrote this script to look through a directory of files, extract a specific part of each file and write it out to a separate text file. Curious if someone can shine some light on what is happening here...
For this part:
if start_line <= i < end_line:
print(line)
# out_f.write(line)
If I run the script with print(line) I get back a "UnboundLocalError: local variable 'end_line' referenced before assignment" error. However, running the script with the out_f.write(line) works as intended.
Second slightly less annoying problem is this part:
for file in os.listdir(os.chdir(target_dir)):
tp_parser(file)
I can't explain to myself why I have to switch to the working directory(i.e. os.chdir(target_dir)) to actually iterate through the files. I'm aware the os.listdir() by itself returns a list of file names but how is that any different if you pass a os.chdir() argument in os.listdir().
Thanks in advance.