Python 尝试检查文本文件中的行中是否存在字符串,但它';它不工作了
正如标题所说,我试图检查txt文件中是否存在字符串并打印该行。我知道在这里和网上有很多帖子,但我试着去关注它们,但没有任何效果。有人能看看我的代码,看看有什么错误或遗漏了什么吗 守则:Python 尝试检查文本文件中的行中是否存在字符串,但它';它不工作了,python,string,loops,file,Python,String,Loops,File,正如标题所说,我试图检查txt文件中是否存在字符串并打印该行。我知道在这里和网上有很多帖子,但我试着去关注它们,但没有任何效果。有人能看看我的代码,看看有什么错误或遗漏了什么吗 守则: x='potato' file=r"C:\Users\transactions.txt" def searchpotato(): with open(file,'r') as read_obj: for line in read_obj: if
x='potato'
file=r"C:\Users\transactions.txt"
def searchpotato():
with open(file,'r') as read_obj:
for line in read_obj:
if x in line:
print(line)
理想的结果是,所有在.txt文件中带有单词“potato”的行都将被打印出来。(土豆好,土豆比西红柿好等等)谢谢。我稍微改变了你的功能,但保留了它的精华。试试
line.lower()
。如前所述,“potato”和“potato”是不同的,但是.lower()
使行中的所有字母都小写
x = 'potato'
file = r"C:\Users\transactions.txt"
def search_x(file, x):
with open(file,'r') as read_obj:
for line in read_obj.readlines():
if x in line.lower():
print(line)
我在我的机器上运行了以下代码,它运行正常
x='potato'
file=r"/var/folders/ql/tt4_4thj5fdd9xrxlpmklsrwygb8j8/T/tmp.wPLDfNsi/something.txt"
def searchpotato():
with open(file,'r') as read_obj:
for line in read_obj:
if x in line.lower():
print(line)
searchpotato()
我唯一能想到的是——你声明了函数,但最后没有调用它
另外,正如Arild所说,如果你不想让你的搜索案例有意义,那么在行中使用.lower()是个好主意。Oops,edited。两者应该是相同的。谢谢错误是什么?没有任何错误,但是没有打印任何内容,尽管txt文件中确实包含带“土豆”的行。您是否在最后校准函数searchpotato()
?谢谢您的回答。