简体   繁体   中英

In Python, searching for line number in file only works once, then only returns 0

I am trying to use Python to edit Abaqus input files, and I need to find which lines have certain headers (eg "*Nodes," "*Elements"). I have code as follows that works correctly:

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

print(headerline)

This prints the correct value, which in this case is 8. However, if I run this back to back, or try to search for another header, it always prints zero for the next header.

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)

Both of those examples print out the correct value for the first headerline, but then give 0 for the next one, even if I'm literally doing the exact same thing.

What am I missing here that is permanently setting it to zero?

You should close the file if you want to use readlines() again.

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)

as far as i know, it automatically closes the file after it has finished reading

Once you've run your code like this it's okay:

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

print(headerline)

later when you want to access the same file again, you will get the value of []

you can learn value, like this:

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

Returns 0 since you can't look for anything with such a value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM