簡體   English   中英

使用Python在txt文件中查找字符串

[英]Find String in a txt file using Python

我有一個相當大的.txt文件-大約70K行。

我正在嘗試使用Python查找字符串“無法更新”的所有實例。

當我打開文件並在“無法更新”上使用ctrl -f時,它會立即找到它。 但是,在Python,.find()或inreg中使用RegEx時,它根本找不到該字符串。 請在下面查看我使用的三種方法:

RegEx方法:

f = open('C:\PerfupD.txt', 'r')

strings = re.findall('Cannot update', f.read())

print(strings)

。找():

with open('C:\PerfUpD.txt', 'r') as file:

    for line in file:

          if line.find('Cannot update') != -1:

              print("Errors found")

如果在:

with open('C:\PerfUpD.txt', 'r') as file:

    for line in file:

          if 'Cannot update' in line:

              print("Errors found")

我什至嘗試搜索“ Ca”,但找不到任何內容,但是當我僅搜索“ C”時,它會找到大量實例...一個側面說明是,該.txt文件是從最初保存該文件的網站生成的文件作為.err文件。 然后,我將其另存為.txt。

我唯一想到的是,也許文件中的數據是以其他形式生成的,但是打開時看起來像常規文本。 非常感謝任何見解!

您可能可以這樣做:

f = open('your file.txt', 'r+')
for line in f:
    if 'Cannot Update' in line:
        print('error found')

無需正則表達式

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM