0

我正在开发一个 Python(3.6) 项目,在该项目中我需要从目录结构中解析一些文本文件。

目录结构为:

--easy(root dir)
----sub_dir
-------another_sub_dir
-----------description(另一个子目录)
------------- ----- description.txt(文件)

我需要遍历子目录中的所有 descriptions.txt 文件,然后将它们解析到数据库中。

description.txt 文件以标准格式格式化为:

从文本段落开始,然后我们有输入、输出、约束、示例 > 输入、输出和解释标题。我们需要将 description.txt 文件保存在数据库中,因为这些标题将转换为数据库表列。

我试图遍历目录结构以找到所有 description.txt 文件:

import os
for root, dirs, files in os.walk(os.path.join('easy')):
    for file in files:
        if file.endswith('description.txt'):
            print(os.path.join(root, file))

通过这种方式,我们可以获得所有 descriptions.txt 文件,但我们如何通过使用该文本文件中的标题来解析它们并将它们保存到数据库中。

我们怎样才能做到这一点?请帮帮我!

提前致谢!

4

1 回答 1

0

您可以将标题保存为列表,然后再将其拆分:-

with open(description.txt) as desc_file:
    Heading1 = "keep reading until you get 2 blank lines in a row"
    Heading2 = "keep reading until you get 2 blank lines in a row"
    .
    .
    Last_ Heading = ditto

现在您可以将这些标题映射到您的表格列。

编辑:- 使用 open 您可能想指定具有哪种编码文件,它因系统而异。

于 2017-12-23T07:52:32.827 回答