2017-07-28 99 views
0

这个问题可能是重复的,但是我发现任何答案都不起作用。我有一个.txt文件,这个充满布局:Python 3:查找文件中的行

艺术家 - 歌曲,www.link.com

artist2 - song2,www.link2.com

这是我的一般用途:

uinput = input("input here: ") 

save = open("save.txt", "w+") 
ncount = save.count("\n") 

for i in range(0, ncount): 
    t = save.readline() 
    if uinput in t: 
     print("Your string " uinput, " was found in" end = "")   
     print(t) 

我的意图是:如果在一行中找到用户输入词,则打印整个行或链接。

回答

1

您可以使用列表理解来读取文件并获得唯一包含字线,例如:

with open('save.txt', 'r') as f: 
    uinput = input("input here: ") 
    found = [line.rstrip() for line in f if uinput.lower() in line.lower()] 
    if found: 
     print('Found in these lines: ') 
     print('\n'.join(found)) 
    else: 
     print('Not found.') 

如果您只想打印链接,可以使用:

found = [line.rstrip().split(',')[1] for line in f if uinput.lower() in line.lower()] 
4
  1. 想要读取文件,但是您正在以写入模式打开文件。您应该使用r,不w+

  2. 最简单的方法来遍历一个文件有一个for循环直接在文件对象

  3. 不是一个错误,但一个挑剔迭代。你不关闭你的文件。你可以用with.. as上下文管理解决这个


uinput = input("input here: ") 

with open("save.txt", "r") as f: 
    for line in f: 
     if uinput in line: 
      print('Match found') 
0

您可以使用列表理解来获取包含用户输入单词的行。使用下面的代码:

try: 
    f = open("file/toyourpath/filename.txt", "r") 
    data_input = raw_input("Enter your listed song from file :"); 
    print data_input 
    fetch_line = [line for line in f if data_input in line] 
    print fetch_line 
    f.close() 
except ValueError, e: 
    print e