Search code examples
python-3.xcommentscobol

Reading a Cobol (.cbl) file in python and extract the commented lines from it


I am having a .cbl file with many lines. I want to read it and extract the commented lines form the same into a .txt file.

For example:

a.  000200* PROGRAM-ID. AP540P00.
(or)
b.        * PROGRAM-ID. AP540P00.

I need to check for * at 7th position. After extracting all the commented lines print it to a text file.

I did this:

with open('AP540P00.cbl', 'r') as f:
    for line in f:
        s = set(line)
        if ('*' in s ):
            print(line)

But I need to specifically check * only at 7th index of every line.


Solution

  • An "*" or "/" in column 7 or "*>" anywhere on the line.
    Write to a text file.
    Python 3.7

    Code:

    line = ''
    fout = open('z:comments.txt', 'wt')
    x = open('z:code.txt', 'rt')
    for line in x:
        if len(line) > 6 and (line[6] == '*' or line[6] == '/' \
                    or line.find('*>') > -1):
                fout.write(line)
    fout.close()
    

    Input:

    000200* PROGRAM-ID. AP540P00.
          * PROGRAM-ID. AP540P00.
           code
           code 
          * comment 1
    
           code 
           code *> in-line comment 
          * comment 2
           code 
           code 
          / comment 3
           code 
           code 
          * comment 4
           code 
           code 
    

    Output:

    000200* PROGRAM-ID. AP540P00.
          * PROGRAM-ID. AP540P00.
          * comment 1
           code *> in-line comment 
          * comment 2
          / comment 3
          * comment 4