簡體   English   中英

如何在文本文件中查找和解析以特定文本開頭的行?

[英]How to find and parse line in text file starting with certain text?

(由 ANSYS Meshing 編寫的 0 網格
節點: (10 (id start end type) (xyz ...))
面孔:(13(id 開始結束類型 elemType)
(v-0 v-1 .. vn right-cell left-cell ...))
單元格: (12 (id start end type elemtype))
parent-face: (59 (start end parent child) (nchilds child0 child1 ...))
)
(2 3)
(10 (0 1 73cb 0))
(13 (0 1 e7ba 0))
(12 (0 1 0 0))

我想讀取一個包含大約 11 行的 .txt 文件。 特別是第 8 行表示給定的文件是二維還是三維。 第 8 行基本上以 (2 和 3 表示三維。為此我編寫了以下代碼。我的輸出應該是“Dimensions = 3”但我無法得到它。有人可以更正我的代碼嗎?>

import os
def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1
root = os.getcwd()
file = "test.txt"
file_name = os.path.join(root, file)
f = open(file_name)
eof = file_len(file_name)
print(eof)
current_pos = 1
row = f.readline()
dimensions = str(row[8])
while current_pos<=eof:
   if row.startswith("(2"):
      print("Dimensions = " + str(dimensions))
      current_pos+= 1

試試這個。

您應該將f.readlines()s一起使用,而不是f.readline() 在文本中8行由7個,因為第一行是由0開始編號定義。

import os
root = os.getcwd()
file = "test.txt"
file_name = os.path.join(root, file)
f = open(file_name)      # Opening the file.
line8 = f.readlines()[7] # Reading line N°_8 from the file.
# If the number '3' is figured in this line then we have '3D' else we have only '2D'
if '3' in line8:          
   dimensions=3
else: 
   dimensions=2
   
print("Dimensions = " + str(dimensions))

[輸出]

Dimensions = 3

暫無
暫無

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

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