如何找到和解析行在文本文件开始与某些文本?



(0)网格由ANSYS编写网格
节点
(13 (id start end type elemType)
(v-0 v-1 ..))V-n右cell左cell…)
cells: (12 (id start end type elemtype))
parent-face: (59 (start end . type)父母孩子)(nchilds child0 child1…))

(2 3)
(10 (0 73 cb 0))
(13 (0 1 e7ba 0))
(12 (0 1 0 0))

我想读一个.txt文件,其中包含大约11行。特别是第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

相关内容

  • 没有找到相关文章

最新更新