Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
python programming help read file?
so i have a .txt file and im doing opening and reading the file in python 3.
but what im stuck is how do i write the code to do a simple IF type statement to read that text?
explained:
i can read the file, i can read individual lines of the file, but lets say in the 2nd line of the file it just has the word 'Hello' or even 'H' on it.
how can i write a code that will say something like
if readline() == 'HELLO'
print('good job')
else:
print('try again')
im trying to not just read the file, which i can do, but write a code where it will be like..... if the second line in the .txt file says 'H' or 'HI'
then you print out whatever
if not you get a message say ing try again.
right now this is my code:
the first line is just the letter H
so how do i do the code that says if the letter on the first line is H in the TEXT FILE., it prints('good job')
print('read one line at a time')
text_file = open('read_it.txt', 'r')
answers = (text_file.readline())
if answers == H:
print('hey')
print(answers)
text_file.close()
1 Answer
- brilliant_movesLv 77 years ago
Try something like this:
print('reading file one line at a time')
text_file = open('read_it.txt', 'r')
answers = (text_file.readlines())
for line in answers:
.... line = line.strip().lower()
.... if line == 'hello':
.... .... print line+': '+'good job!'
.... elif line == 'hey':
.... .... print line+': '+'hey yourself'
.... else:
.... .... print line+': '+'try again.'
text_file.close()