当前位置: 代码迷 >> python >> 如何使python代码读取.txt文件中的特定文本行?
  详细解决方案

如何使python代码读取.txt文件中的特定文本行?

热度:22   发布时间:2023-07-14 08:46:10.0

所以我一直在摆弄python和英雄联盟。 我发现您可以在游戏中做笔记。 所以我考虑过让python代码从游戏中的注释中读取一行文本,例如“ Lux no flash”,但它似乎根本无法读取,只有当我手动执行时它才能工作使用完全相同的代码。 这是我的代码:

import os
import time
def main():
    os.chdir('C:\\Riot Games\\League of Legends\\RADS\\solutions\\lol_game_client_sln\\releases\\0.0.1.237')
    f=open("MyNotes.txt", "r")
    if f.mode == 'r':
        lines=f.readlines()
        text = lines[4]
        time.sleep(0.1)
        if text == 'Lux no flash':
           print('Done')
        else:
            print('Something went wrong')
    f.close()
if __name__== "__main__":
 main()

输出是“出了点问题”,但是当我手动执行时,它说“完成”。 我觉得python无法阅读联赛代码。 也许你们知道该怎么做...这是.txt文件,我正在尝试访问:

##################################################
2018-09-13_18-57-33_
##################################################
Lux no flash

我只是假设一个文件:

 # cat MyNotes.txt there is Lux no flash in line there is Something went wrong There is nothing lux no flash this is all test 

因此,只要在文件中寻找'Lux no flash'一词,我们就可以按照以下步骤进行操作。但是它区分大小写。

始终最佳做法是with open()方法一起使用来读取文件。

import os
import time
def main():
       with open("MyNotes.txt") as f:
        for line in f.readlines():
            if 'Lux no flash' in line:
                print('Done')
            else:
                print('Something went wrong')
if __name__== "__main__":
    main()

输出结果将是:

 Done Something went wrong Something went wrong Something went wrong 

即使尝试使用lux.txt ,它也可以按我的代码预期的那样工作。

 import os import time def main(): with open("lux.txt") as f: for line in f.readlines(): #line = line.strip() # use can use the strip() or strip("\\n") #line = line.strip("\\n") # if you see white spaces in the file if 'Lux no flash' in line: print('Done') else: pass if __name__== "__main__": main() 

结果出局为:

# test.py
Done

使用lux.txt

##################################################
2018-09-13_18-57-33_
##################################################
Lux no flash

码:

content = []
with open('lux.txt', 'r') as f:
    for line in f:
        content.append(line.strip('\n'))

    for i in content:
        if 'Lux no flash' == i:
            print("Done")
        else:
            pass

更好的 @pygo

with open('lux.txt', 'r') as f:
    content = f.read()
    if 'Lux no flash' in content:
        print("Done")
    else:
        print("No else, this works :)") 

输出:

 (xenial)vash@localhost:~/python/stack_overflow$ python3.7 lux.py Done