[英]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)
我找到了'a word'所在的行,我想把这些行变成一个变量
但它只读取文本文件的第一行
我该如何解决
@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()
您可以做的是检查行中的字符串。 这会为你做的。
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)
但是,如果存在更多相同的单词,您可以使用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.")
您可以简单地遍历这些行,并将该行分配给先前创建的字符串变量,如果满足条件,则该字符串出现在文件的一行中:
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()
您还可以创建一个列表,其中包含字符串出现的每一行:
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.