Python读取行数

时间:2019-05-16 16:54:04

标签: python class readlines

我只是想查询将文本文件的行读回到dict或class对象的最佳方法。

我写入文本文件的数据非常原始,因此我相信可能会有更好的格式化方法。

基本上,数据看起来像这样(-是我的评论):

Default_scene --this is the scene name 
0 -- start frame
10 --end frame
--this could be a filepath but is blank
2 --number of records in class object can vary but 2 here
Dave01: --record name 
Dave01: -- namespace
V:/assets/test.fbx --filepath for record
1 -- number of export sets (can vary)
Test:Default_scene_Dave01 0-10 --export set
Test01: --record name
Test01:--namespace
C:/test2.fbx --filepath
0--number of export sets

例如:如果我想将记录数据读回到对象类中,我将如何告诉读取行脚本读取下一行或什至两行,具体取决于可能有​​多少个导出集?

非常感谢!

2 个答案:

答案 0 :(得分:1)

也许类似的方法可以工作,然后您将所有内容都放在列表中并可以使用它:

lines = []
with open(filepath) as fp: 
   line = fp.readline()
   lines.append(line)
   while line:
       line = fp.readline()
       lines.append(line)

答案 1 :(得分:1)

您阅读的行告诉您首先有多少个导出集,然后然后阅读更多的行要处理。基于您的评论的代码可能看起来像

with open("data.txt") as f:
    scene_name = next(f).strip()
    start_frame = int(next(f))
    end_frame = int(next(f))
    num_recs = int(next(f))
    for _ in range(num_recs):
        rec_name = next(f).strip()
        namespace = next(f).strip()
        fpath = next(f).strip()
        num_export_sets = int(next(f))
        export_sets = [next(f).strip() for _ in range(num_export_sets)]
        # ...
相关问题