首页 > 解决方案 > 在 python 中读取 Cobol (.cbl) 文件并从中提取注释行

问题描述

我有一个包含很多行的 .cbl 文件。我想阅读它并将注释行从相同的形式提取到 .txt 文件中。

例如:

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

我需要*在第 7 位进行检查。提取所有注释行后,将其打印到文本文件中。

我这样做了:

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

但我只需要专门检查*每行的第 7 个索引。

标签: python-3.xcommentscobol

解决方案


第 7 列中的“*”或“/”或该行任意位置的“*>”。
写入文本文件。
蟒蛇 3.7

代码:

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()

输入:

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 

输出:

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

推荐阅读