【问题标题】:In Python, searching for line number in file only works once, then only returns 0在 Python 中,在文件中搜索行号只工作一次,然后只返回 0
【发布时间】:2020-09-25 08:06:17
【问题描述】:

我正在尝试使用 Python 来编辑 Abaqus 输入文件,并且我需要找出哪些行具有某些标题(例如“*Nodes”、“*Elements”)。我有如下代码可以正常工作:

headerline = 0
for line in input.readlines():
    if line.lower().startswith('*node'):
        break 
    headerline = headerline + 1

print(headerline)

这会打印正确的值,在本例中为 8。但是,如果我背靠背运行,或者尝试搜索另一个标题,它总是为下一个标题打印零。

headerline = 0
for line in input.readlines():
    if line.lower().startswith('*node'):
        break 
    headerline = headerline + 1

print(headerline)

headerline = 0
for line in input.readlines():
    if line.lower().startswith('*node'):
        break 
    headerline = headerline + 1

print(headerline)
headerline = 0
for line in input.readlines():
    if line.lower().startswith('*node'):
        break 
    headerline = headerline + 1

print(headerline)

headerline2 = 0
for line in input.readlines():
    if line.lower().startswith('*element'):
        break 
    headerline2 = headerline2 + 1

print(headerline2)

这两个示例都打印出第一个标题行的正确值,然后为下一个标题行给出 0,即使我确实在做完全相同的事情。

我在这里遗漏了什么将其永久设置为零?

【问题讨论】:

  • herehere 讨论了同样的问题。

标签: python header abaqus readlines startswith


【解决方案1】:

如果你想再次使用 readlines(),你应该关闭文件。

headerline = 0
for line in input.readlines():
    if line.lower().startswith('*node'):
        break 
    headerline = headerline + 1

print(headerline)

input.close()
input=open(...)

headerline2 = 0
for line in input.readlines():
    if line.lower().startswith('*element'):
        break 
    headerline2 = headerline2 + 1

print(headerline2)

【讨论】:

    【解决方案2】:

    据我所知,它读完后会自动关闭文件

    一旦你像这样运行你的代码就可以了:

    input = open(.........)
    headerline = 0
    for line in input.readlines():
        if line.lower().startswith('*node'):
            break 
        headerline = headerline + 1
    
    print(headerline)
    

    稍后当你想再次访问同一个文件时,你会得到[]的值

    你可以像这样学习价值:

    print(input.readlines())#output:[]
    

    返回 0,因为您无法查找具有此类值的任何内容

    【讨论】:

      猜你喜欢
      • 2015-06-18
      • 2022-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-28
      相关资源
      最近更新 更多