Python 显示文件中包含关键字的所有行。
我正在尝试创建一个程序,它读取一个文本文件并要求用户输入一个单词,然后该程序将打印包含该行的所有行 这是我目前的代码:Python 显示文件中包含关键字的所有行。,python,Python,我正在尝试创建一个程序,它读取一个文本文件并要求用户输入一个单词,然后该程序将打印包含该行的所有行 这是我目前的代码: f = open ("G:/test.txt", "r"); line = f.readlines() find_word = raw_input("Enter word here:") if find_word in f: print find_word f.close() 这应该起作用: 在处理文件时使用和语句,因
f = open ("G:/test.txt", "r");
line = f.readlines()
find_word = raw_input("Enter word here:")
if find_word in f:
print find_word
f.close()
这应该起作用:
在处理文件时使用和
语句,因为它负责关闭文件
with open("G:/test.txt") as f:
final_word=raw_input("Enter word here:")
for line in f: #iterate over each line of f
if final_word in line: #if final_word in line , then print it
print line.strip()
这应该起作用:
在处理文件时使用和
语句,因为它负责关闭文件
with open("G:/test.txt") as f:
final_word=raw_input("Enter word here:")
for line in f: #iterate over each line of f
if final_word in line: #if final_word in line , then print it
print line.strip()
您的行列表包含如下词语:
['dom\n', 'hello\n', 'world']
注意到新词了吗?你需要脱掉它们
line = open("test.txt").read().splitlines()
find_word = raw_input("Enter word here:")
if find_word in line:
print find_word
您的行列表包含如下词语:
['dom\n', 'hello\n', 'world']
注意到新词了吗?你需要脱掉它们
line = open("test.txt").read().splitlines()
find_word = raw_input("Enter word here:")
if find_word in line:
print find_word
这个循环不应该是:行中的
吗?这是一个可怕的问题标题。史诗失败标题和史诗失败问题。我没有看到问号。这个循环不应该是:
行中的吗?这是一个可怕的问题标题。Epic fail title和Epic fail question。我没有看到问号。@user1780144如果它对您有效,请单击勾号。“print line”(带逗号)而不是“print line.strip()”也可以。在python3中,您可以使用print(line,end=“”)来抑制换行。@如果用户1780144对您有效,请单击勾号。“print line”(带逗号)而不是“print line.strip()”也可以。在python3中,可以使用print(line,end=“”)来抑制换行。