0

My code iterates through the txt files in a folder and then extracts headers (the line containing "| SYS" and writes them to another file. However, when the file is not found the code simply fails without an error. E.g. it searches through files containing USR02, USR06, 1251 and TEXTS in file name. But when some file containing e.g. 1251 is not found it does not search for the next file containing "TEXTS". There is no error message. Any ideas?

from glob import glob
import fileinput

table02 = ('FINAL' + '\\'+ '0a_USR02.txt')

with open(table02, 'w') as out:
    for line in fileinput.input(glob('*USR02.txt')):
        if '|   SYS' in line:
            out.write(line)

table06 = ('FINAL' + '\\'+ '0a_USR06.txt')

with open(table06, 'w') as out:
    for line in fileinput.input(glob('*USR06.txt')):
        if '|   SYS' in line:
            out.write(line)

table09 = ('FINAL' + '\\'+ '0a_AGR_TEXTS.txt')

with open(table09, 'w') as out:
    for line in fileinput.input(glob('*TEXTS.txt')):
        if '|   SYS' in line:
            out.write(line)

table03 = ('FINAL' + '\\'+ '0a_AGR_1251.txt')

with open(table03, 'w') as out:
    for line in fileinput.input(glob('1251.txt')):
        if '|   SYS' in line:
            out.write(line)
Moldovan Daniel
  • 1,521
  • 14
  • 23
user9799161
  • 123
  • 2
  • 14
  • 1
    Check the folder to see if a file is created. (Also relevant: [How do I check whether a file exists without exceptions?](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions)) – TrebledJ May 24 '19 at 12:52
  • 1
    Possible duplicate of [How do I check whether a file exists without exceptions?](https://stackoverflow.com/questions/82831/how-do-i-check-whether-a-file-exists-without-exceptions) – Devesh Kumar Singh May 24 '19 at 12:54
  • You're ignoring all errors. Of course there's going to be no error message. Remove the try-except blocks, or at least narrow the `except` to the specific type of error you want to ignore and/or print the exceptions so you can see what's going on. – glibdud May 24 '19 at 13:24

1 Answers1

0

A complete overhaul where the group of files have all lines containing particular expression written into one file grouped by their name.

from glob import glob
import fileinput
import os


cwd = os.getcwd()
directory = cwd

flatfiles = ['UST04', 'USR02', 'USR06','1251', 'AGRS', 'TEXTS',\
             'USERS', 'FLAGS', 'DEVACCESS', 'USERNAME', 'TSTC', 'TSTCT']
for flatfile in flatfiles:
    for file in os.listdir(directory):
        if file.endswith(flatfile + ".txt"):
            table03 = ('FINAL' + '\\'+ '0a_' + flatfile + '.txt')
            with open(table03, 'w+') as out:
                for line in fileinput.input(glob('*'+ flatfile +'.txt')):
                    if '|   SYS' in line:
                        out.write(line)
        else:
            pass
user9799161
  • 123
  • 2
  • 14