[英]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我找到了'a word'所在的行,我想把这些行变成一个变量
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: @Maicon 有它,尽管在 python 中你甚至不需要全局变量,你可以在
if
语句中创建和设置desired_line
,它的命名空间将扩展到包含if
语句的整个 function :
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.但是,如果存在更多相同的单词,您可以使用
dict
来获取行号和值。
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.