0

i want to search for a variable "elementid" in a txt file

  f = open("wawi.txt", "r")
  r = f.read()
  f.close()
  for line in r:
      if elementid in line:
          print("elementid exists")
          break

the elementid is maybe 123456

the txt contains three lines:

1235
56875
123456

but the code does not print "elementid exists", why ? I work with python 3.4

Steffen
  • 51
  • 1
  • 4

4 Answers4

0

When you read the file you read the whole thing into a string.

When you iterate over it you get one character at a time.

Try printing the lines:

for line in r:
     print line

And you'll get

1
2
3
5

5
6
8
7
5

1
2
3
4
5
6

You need to say:

for line in r.split('\n'):
    ...
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Just rearranging your code

f = open("wawi.txt", "r")
for line in f:
    if elementid in line: #put str(elementid) if your input is of type `int`
        print("elementid exists")
        break
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49
  • it works but he says that 258311 is the same as 25831. So i tried with elementid == line but this does not work – Steffen Mar 24 '15 at 12:59
0

Convert the integer to a string THEN iterate over the lines in the file, checking if the current line matches the elementid.

elementid = 123456 # given
searchTerm = str(elementid)
with open('wawi.txt', 'r') as f:
    for index, line in enumerate(f, start=1):
        if searchTerm in line:
            print('elementid exists on line #{}'.format(index))

Output

elementid exists on line #3

Another approach

A more robust solution is to extract all numbers out of each line and find the number in said numbers. This will declare a match if the number exists anywhere in the current line.

Method

numbers = re.findall(r'\d+', line)   # extract all numbers
numbers = [int(x) for x in numbers]  # map the numbers to int
found   = elementid in numbers       # check if exists

Example

import re
elementid = 123456 # given
with open('wawi.txt', 'r') as f:
    for index, line in enumerate(f, start=1):
        if elementid in [int(x) for x in re.findall(r'\d+', line)]:
            print('elementid exists on line #{}'.format(index))
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0
f = open("wawi.txt", "r")

for lines in f:
    if "elementid" in lines:
        print "Elementid found!"
    else:
        print "No results!"
jester112358
  • 465
  • 3
  • 17