Search code examples
pythonstringfilesearchtext

Python: I can't find a string inside an Excel file exported to .txt: only one char


I exported an Excel sheet in TXT format; upon reading it in Python, I am not able to find strings insde it.

I tried several methods, none works: each one works only if I look for one character long string! Why?!?

fname="elenco.txt"

counter=0
for line in open(fname):
    counter = counter + 1
    if counter>5:
        break
    if "AB" in line:
        print "funziona"
    print line
    
with open(fname, 'r') as inF:
    for line in inF:
        if 'T' in line:
            print "OK"
    
with open(fname) as f:
    content=f.readlines()
counter=0
for rec in content:
    test=rec[:len(rec)-5]
    print test, ">>>",test.find('TORINO')
    counter = counter + 1
    if counter>5:
        break
    #if rec.find("ABBIA")>0:
    #   print "Trovato: " + rec
print "Fine."

Solution

  • This is weird: I figured out that the error was not in source code, but in text file! Although it has .txt suffix and it looks like a standard text file in PSPad, it's not: running the script from DOS I discovered that there are "spaces" between each letter in the file... so I examined it with an hex editor, and I found that it's an unicode file!! I don't know why it happened, I obtained the file by saving an Excel .xls file in .txt format.