繁体   English   中英

如何在Python中的文本文件中查找特定的字符串

[英]How to find specific Strings in text file in Python

while True:
contents = pyperclip.paste() #paste from clipboard
filepath = r"C:\Users\BOT\Desktop\DATA.txt"
with open(filepath, 'w') as f: # 'w' means write mode and we get the file object as f
                        f.write(contents)
                        f.close() #write on DATA.txt, save
                with open(filepath, 'r') as f:(edited)

==============这给DATA.txt这个文本:

440    Entry Short    Short    2018-04-01 17:37:00    6479.5    
    Exit Short    Close position order    2018-04-01 17:39:00    6477    17    42.5
441    Entry Long    Long    2018-04-01 17:39:00    6477    
    Exit Long    Close position order    2018-04-01 17:41:00    6513.5    51    1861.5
442    Entry Short    Short    2018-04-01 17:41:00    6513.5    
    Exit Short    Close position order    2018-04-01 17:43:00    6503    68    714
443    Entry Long    Long    2018-04-01 17:43:00    6503    
    Exit Long    Close position order    2018-04-01 17:44:51    6517    85    1190
444    Entry Short    Short    2018-04-01 17:45:06    6518.5    
    Exit Short    Open
445    Entry Short    Short    2018-04-01 18:45:06    6525.5    
    Exit Short    Open

如何找到最后一个这样的字符串? “ Exit Short Open”输出此处应为2

filepath = r"C:\Users\BOT\Desktop\DATA.txt"
                with open(filepath, 'w') as f: # 'w' means write mode and we get the file object as f
                        f.write(contents)
                        f.close()
                with open(filepath, 'r') as f: 
                        f.read(contents)
                        if 'Exit Short    Open' in open.f.read():
                        print('Exit Short    Open')
                        f.close()

不工作

也许contents.count('Exit Short Open')可以解决问题? 像这样:

while True:
    contents = pyperclip.paste() #paste from clipboard
    filepath = r"C:\Users\BOT\Desktop\DATA.txt"
    with open(filepath, 'w') as f: # 'w' means write mode and we get the file object as f
        f.write(contents)
        # f.close() no need to close the file, "with" operator does that automatically
    with open(filepath, 'r') as f:
        count_var = f.read().count('Exit Short    Open')
        print(count_var)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM