spoon_man
spoon_man

Reputation: 11

How to read a text file and check against its contents with python

I am attempting to read a text file, print its contents, and stop when it reaches the "flag".

My code is:

 import sys
 sys.path.append("/Libraries/Documents")
 file = open("readmepython.txt", "r")
 while True:
     x = file.readline()
     if x != "break":
         print(x)
     else:
         break

 #doesnt work

The text file in question has only this inside of it with no extra spaces or returns:

this is the ip
this is the /24
this is the gateway
this is the name server
break

The loop will continue to run infinitely, and I am unsure how to properly assign the variable so that it checks properly.

Does python not assign the raw string value when reading from a text file? What am I doing wrong here?

Upvotes: 0

Views: 2123

Answers (3)

joel goldstick
joel goldstick

Reputation: 4483

import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
    x = file.readline().strip()
    if x != "break":
      print(x)
    else:
      break

Upvotes: 0

spoon_man
spoon_man

Reputation: 11

While many of the answers were extremely helpful for other issues I had, none explicitly answered the question. I have used Mr.Mean's suggestion of .replace to clear up the hidden characters that are returned in text documents. Another user showed me .strip() (something I should have known), which works much better to strip away the hidden characters.

When reading from a text document in Python, if one pressed enter for a new line there will be an unseen

\n

at the end of the string, which will be enclosed with single quotes ' '.

I ended up using the .replace methode twice to clear the string into what I wanted. This could have also been done by slicing the first character, and last three characters of the string.

My new, functional code:

import sys
sys.path.append("/Libraries/Documents")
file = open("readmepython.txt", "r")
while True:
    x = file.readline().strip
    if x != "break":
      print(x)
    else:
      break

#does work

I will end up accepting this answer unless someone suggests otherwise.

Upvotes: 0

Mark_Eng
Mark_Eng

Reputation: 503

Try something like,

file = open("readmepython.txt", "r")
For line in file:
   print line

or

file = open("readmepython.txt", "r")
For line in file.readlines():
    print line

see also:python looping through input file

Upvotes: 1

Related Questions