简体   繁体   中英

read and get specific int line of the text file into variable on python

a_file = open('file.txt')
string = 'a word'
flag = 0
index = 0
for line in a_file:
    index += 1
    if string in line:
      break
index -= 1

lines_to_read = [index]

for position, line in enumerate(a_file):
    if position in lines_to_read:
        file = line
print(line)

I found the line where 'a word' is located, and I want to get those line into a variable

but it only reads the first line of the text file

how can I fix it

@Maicon has it, though in python you don't even need the global variable, you can create and set desired_line in the if statement and its namespace will extend to the entire function containing the if statement:

a_file = open('file.txt')
string = 'a word'
for line in a_file:
    if string in line:
        desired_line = line
        break

print(desired_line)

a_file.close()

What you can do is check for string in the line. This will do for you.

a_file = open('all.txt')
string = 'a word'
flag = 0
index = 0
for position, line in enumerate(a_file): 
    if string in line: #=== if 'a word' in line
        file = line
        pos=position+1
        break
print(file,"Line Number: ",pos)

However if more number of the same words are there, you can use a dict to get the line numbers and the value.

a_file = open('all.txt')
string = 'f'
dictionary={}
flag = 0
index = 0

for position, line in enumerate(a_file): 
    if string in line:
        file = line
        pos=position
        dictionary.update({pos+1:[file.strip("\n").strip(),file.count(string)]})
if dictionary!={}:
    print("\n------- Statistics --------\n")
    print("Total Items found: ",len(dictionary),"\nTotal Occurences: ",sum([dictionary.get(x)[1] for x in dictionary]))) #=== Get the sum of all numbers

    for key, value in dictionary.items():
        print("-------------------------")
        print("Line: "+value[0],"\nNumber of occurrences: ",value[1],"\nLine Number: ",key)
        
else:
    print("Oops. That word was no found. Check you word again.")

You can simply iterate through the lines, and assign the line to a previous created string variable, if the condition is met, that the string occurs in a line of the file:

a_file = open('file.txt')
string = 'a word'
res_line = ""

for line in a_file:
    if string in line:
        res_line = line

print(res_line)

a_file.close()

you could also create a list which contains every line in that the string occurs:

a_file = open('file.txt')
string = 'a word'

res = [line for line in a_file if string in line]
print(res)

a_file.close()

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