簡體   English   中英

Python -> 讀取文件並創建 3 個列表,其中包含 3 個字符串,例如用於划分文件的標記

[英]Python -> Read file and create 3 lists with 3 strings like markers to divide file

這是我第一次與 Python 會面:) 我有問題 -> 我的代碼和問題如下:

我正在嘗試將輸入文件分成 3 個文件(程序信息/程序核心/工具列表)

  • 我可以像我想要的那樣匹配和編寫第一部分(在行中找到字符串時中斷循環),

我怎么知道我想“繼續從這個找到的字符串循環”並寫入第二個列表/文件,或者我如何標記兩個字符串之間的所有行以將其附加到列表中並在之后寫入 do 文件。 非常感謝你。 祝你聖誕快樂,會因為你的幫助而快樂

import os

filename = "D327971_fc1.i"                  # current program name
file = open(filename, 'r')                  # read current program

if os.stat(filename).st_size == 0:          # check if size of file is null
    print('File is empty')
    file.close()
else:
    read = file.readlines()
    programdef = []
    toollist = []
    core = []
   
    line_num = -1
    for line in read:
    
        start_line_point = "Zacatek" in line
        end_line_point = "Konec" in line
        toollist_point = "nastroj" in line
  
        programdef.append(line.strip())
        if start_line_point: break
        core.append(line.strip())           
        if end_line_point: 
        toollist.append(line.strip())  
        
    with open('0progdef.txt', 'w') as f:
       f.write(str(programdef)) 
    with open('1core.txt', 'w') as f:
       f.write(str(core))
    with open('2toollist.txt', 'w') as f:
       f.write(str(toollist))

通過查找字符串將輸入文件分成 3 個帶有標記線的列表,然后將該列表轉為 3 個文件。

如果我理解正確的話,你想要的是將文件分成 3 個不同的文件:第一個包括“Zacatek”之前的所有行,第二個包括“Zacatek”和“Konec”之間的所有行,第三個包括所有行在“Konec”和“nastroj”之間。

您可以將for循環更改為:

keywords = {0:'Zacatek', 1:'Konec', 2:'nastroj'}
index = 0

for line in read:
    if index == 3:
        break
    if keywords[index] in line:
        index += 1
        continue
    if index == 0:
        programdef.append(line.strip())
    elif index == 1:
        core.append(line.strip())
    elif index == 2 : 
        toollist.append(line.strip())

這將創建三個預期的文件,其中包含原始文件中的行lists

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM