【问题标题】:Python parse all lines inside of a files and split them by folder structurePython解析文件中的所有行并按文件夹结构拆分它们
【发布时间】:2021-11-30 23:37:09
【问题描述】:

我在 MyFolder 中有一堆文件,我需要像这样拆分它们:

我的文件.txt:

    C:/Storage/agent/temp/6620/sw/main/folder/Module/Types.h
    C:/Storage/agent/temp/6620/sw/main/folder/Module2/Types1.h
    C:/Storage/agent/temp/6620/sw/folder/folder/Module3/Type.h
    etc..

我需要将所有行拆分为这种格式,因为 temp (6620) 之后的这个文件夹正在改变,而且 'sw' 之前的所有内容都可能改变,所以我想将它们作为一部分保留,以便我可以做其他东西在“右侧”,输出应该是:

BUILD_DIRECTORY(C:/Storage/agent/temp/6620)+sw(sw)+base_folder(main)+folder(folder)+module(Module)+file(Types.h)

重点是 sw 总是在 BUILD_DIRECTORY 之后,base 文件夹总是在 sw 之后,模块总是在文件之前。

我的尝试没有成功,我设法获得了 BUILD_DIRECTORY 和 REST,但是 sw 总是丢失,我想有更好的方法来做到这一点:

for filename in files:
    with open(filename, 'r') as file:
        content = file.read().split('\n')
        for line in content:
            if not line: continue
            # Seperate full path to the module in variables
            BUILD_DIRECTORY, REST= line.split('/sw')

希望我的问题足够清楚。 欢迎任何建议,谢谢!

【问题讨论】:

    标签: python python-3.x string file parsing


    【解决方案1】:

    所以一段时间后,我设法得到了我需要的东西,这可能不是最好的解决方案,但它确实有效:

    for filename in files:
        with open(filename, 'r') as file:
            content = file.read().split('\n')
            for line in content:
                if not line: continue
                # Seperate full path to the module in variables
                BUILD_DIRECTORY, SW= line.split('sw/')
                sw+base_folder+folder+module+file = sw.split('\\')
    

    【讨论】:

      猜你喜欢
      • 2018-05-22
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 2014-09-02
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      • 1970-01-01
      相关资源
      最近更新 更多