.readline not printing a letter instead of a line - python-3.x

keywords = open("keywords.txt", "r")
problem = input("Please give us a simple description of the problem you are having with your phone, so we can identify the solution and give it to you...")
if "screen" in problem:
print(keywords.readline())
elif "water" in problem:
print(keywords.readline(2))
elif "battery" in problem:
print(keywords.readline(3))
elif "dropped" in problem:
print(keywords.readline(4))

keywords.readlines() is what you are looking for.
keywords.readline() is taking only one line so that if you say keywords.readline(1) It will return second letter in first line

Related

Removing a line from a file

I have a file named (data.txt):
243521,Biscuit,Flour:Cream,89.5,9,1
367534,Bread,Flour,67.3,1,2
463254,Chocolate,Cocoa butter:Sugar:Milk powder,45.6,4,0
120014,Buns,Wheat Flour,24.9,5,2
560214,Cake,Flour:Baking Powder:Cake Mix,70.5,3,1
123456,burger,bread crumbs:beef:tomato,99.9,10,0
The numbers after the last comma is sold items. I want to write a code that can delete a line just if the number after the last comma is 0. This is the code I wrote but it removes the line even if the number after the last comma is not zero :
productID=input("")
with open("data.txt","r+") as file:
lines= file.readlines()
file.seek(0)
for line in lines:
productInfo= line.split(",")
y=0
if productInfo[5]>"0":
if y==0:
print("Product cannot be removed: sold items must be 0")
y=1
elif productID not in line:
file.write(line)
file.truncate()
print("Product is removed successfully")
I regret that I do not understand what you are asking for. If you have trouble expressing a difficult question, try asking the question to a friend, and then write down what you say.
Other than the noise that y introduces for no reason, the other odd thing about this code is this comparison:
productInfo[5]>"0"
Probably that comparison does not do what you expect.
I believe you just want to know if the last token is a "0" or not. For this it is better to test for equality or inequality, instead of attempting to perform a value comparison of two strings.
String equality can be tested with ==. Check for inequality with !=.
I believe you want this:
productInfo[5] != "0"
From what I have understood, you have a file that contains comma-separated data and last value is of your interest. If that value is 0, you want to remove that line.
General idea is to read the lines in file and split the , in line and access last item. Your mistake is, as many have pointed out, you are trying to compare strings with > which is not valid in python. Following code works for me with your sample data:
#reading the lines in data as list
with open("data.txt", "r") as f:
lines = f.readlines()
new_array = []
#empty array so we can populate it with lines that don't have a 0 at the end
user_input = input("Enter a number: ") #Capturing user input
for line in lines: #iterating over all lines
line = line.split(",") #splitting , in line
if line[len(line)-1].strip() != "0" and line[0] != user_input:
#if first item and last item are not user input and 0 respectively
new_array.append(",".join(line))
elif line[len(line)-1].strip() == "0" and line[0] != user_input:
#if last item is 0 but first item is not user input
new_array.append(",".join(line))
else:
print("ignoring:", *line)
with open("data2.txt", "w") as f: #creating new data file without 0
f.writelines(new_array) #writing new array to new datafile
#data2.txt now contains only lines that have no 0 at the end

Code not checking if inputted answer is correct

I am trying to create a multiple choice quiz that takes questions from an external .txt file and prints it in python. The text file is laid out like this:
1,Who was the first man to walk on the moon?,A.Michael Jackson,B.Buzz Lightyear,C.Neil Armstrong,D.Nobody,C
When I run the code and input the right answer it still says incorrect but continues to say the answer I inputted.
In the code I split each line in the text file by a ',' so the correct answer in the text file is always detail[6]. In the code I have put:
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I thought this would work as it is checking the inputted answer against detail[6] but it always comes out as incorrect.
import random
score=0
with open('space_quiz_test.txt') as f:
quiz = f.readlines()
questions = random.sample(quiz, 10)
for question in questions:
detail = question.split(",")
print(detail[0],detail[1],detail[2],detail[3],detail[4],detail[5])
print(" ")
answer=input("Answer: ")
while True:
if answer.upper() not in ('A','B','C','D'):
print("Answer not valid, try again")
else:
break
if answer.upper() == detail[6]:
print("Well done, that's correct!")
score=score + 1
print(score)
elif answer.upper() != detail[6]:
print("Incorrect, the correct answer is ",detail[6])
print(score)
I would like the code to be able to check if the inputted answer is correct by checking it against detail[6] within the text file, instead of always coming out as incorrect, the correct answer is detail[6].
The problem is that readlines() retains the newline character at the end of each line.
Your detail[6] is something like 'C\n' rather than 'C' itself. To fix that, use
detail = question.strip().split(",")

Why is my program refrenceing the readline command multiple times and how do I stop it

Okay. So I am trying to make a code which is basically a guess the word game. since it is for a school assignment there are certain required parts such as the used of 4 functions and those functions doing certain things. the program need to pull information off of an words sheet which is stored on an external .txt file. When I try to use a line from said using the readline command it will move to the next line every time I reference the function which leaves me in a pickle.
Here is the code
import random
#Variables
file = open('words.txt','r')
Number_of_lines = 0
Correct = 'Place holder'
Score = 0
#Retrieve the next word through readline command
def get_a_Word():
Basic_Word = file.readline()
Word = Basic_Word
Word = Word
return Word
#Turn the word into a guess word
def guess_Word():
Word = get_a_Word()
Edited_Word = '*' + Word[1:]
return Edited_Word
def check_Word(Word):
if Word == get_a_Word():
return True
else:
return False
#Put that shit together
def Main():
Line = 0
while Line < 10:
Edited_Word = guess_Word()
Score = 0
Line = Line + 1
Word = input('Given {} What is the word? '.format(Edited_Word))
Word = Word.upper()
if check_Word(Word) == True:
print('That is correct!')
Score = Score + 10
elif check_Word(Word) == False:
print('That is incorrect. the word was {}.'.format(get_a_Word()))
else:
print('you broke it')
Correct = Score/10
print('You have successfully guessed {} out of 10 words. Your final score is {}.' .format(Correct, Score))
Main()
file.close()
The .txt File contains these word in this order
Store
Apple
Bicycle
Water
Mercedes
Classroom
Architect
Elevator
Measurement
Godzilla
Any help would be appreciated!
I don't know exactly how the functions you're supposed to have are specified, but the obvious solution to not getting multiple different words is simply not to call get_a_Word more than once per cycle of the main loop. Some of the other functions may need to be changed to take the previously fetched word as an argument.
The loop would look something like this (pseudocode, I may be skipping some things):
while line < 10:
word = get_a_Word()
edited_word = guess_Word(word)
guess = input('Given {} What is the word? '.format(edited_word))
if check_Word(word, guess):
print('That is correct!')
score += 10
else:
print('That is incorrect. The word was {}.'.format(word))
A note on naming, unrelated to your issue: Python convention for naming variables and functions is to use lowercase_names_with_underscores for everything, unless the code is mimicking an existing API that uses a different convention. Use CapitalizedNames for classes, and ALL_CAPS for constants.
The most important thing though, is to to be consistent. Your current code seems to have a mix of underscores, capitalization and other styles without any logic to it. Pick one style (even if it's not the one I described in the previous paragraph) and stick to it. (This can be hard to do if your instructor is inconsistent in naming style. Alas there may not be much you can do about that.)

How can i check to see if somethings already written to a txt and give an error if so python

I am doing a school project and I have to make a voting system that uses a voting code. I need help with the code that opens up the 2 files, checks to see if the code is there and gives a value error if it is.
while True:
Code = input("Enter your 6 digit code: ")
try:
Code = int(Code)
if "0" in str(Code): break
if len(str(Code)) != 6 : raise ValueError
else: break
readt = open("Trump.txt" , "r")
readh = open("Clinton.txt" , "r")
readhh = readh.read()
readtt = readt.read()
if Code in str(readtt) or Code in str(readhh): raise ValueError
else: break
readt.close()
readh.close()
except ValueError:
print("Invalid")
Here are a couple pointers to fix your program:
The if len ... else part seems to leave the while loop either through raise or break. The code that does open is never executed.
Also you call open a lot of times. This will become problematic because leaking file descriptors is a problem. Use the with open(...) statement for this. This way, you cannot leave the file open by accident. Your close statements are behind another if ... else construction that will leave the loop in every case.
Your variable names are a bit opaque, perhaps you want to invent some more telling ones.
Why are there two files? Shouldn't there be only one file that contains all the used codes?
Assuming that you presented all the information in your question this is the solution for your problem:
def code_checker():
codes = []
with open('Trump.txt', 'r') as f1:
for line in f1:
codes.append(line.rstrip())
with open('Clinton.txt', 'r') as f2:
for line in f2:
codes.append(line.rstrip())
code = input('Enter your 6 digit code:\n')
while True:
if '0' in code or len(code) != 6:
print('Invalid code\n')
code = input()
continue
elif code in codes:
raise ValueError
code_checker()

Answers won't show up as correct in python vocab test?

This is the coding that I have so far. The basic concept is that you have a separate file to type in the answers and then the program accesses the separate file and draws information from it.
#!/usr/bin/python3.2
# -*-coding:Utf-8 -*
#Vocabulary/translation quiz
import os
import random
keep_adding=input("Would you like to start a new quiz ? If yes, press \"S\" : ")
with open("data.txt","a") as f: #look for the file data.txt for the questions
while keep_adding=="S": #ongoing action to look for the answer
word=input("Enter a word : ")
translation=input("And its translation : ")
f.write("{0},{1},\n".format(word,translation))
keep_adding=input("To continue, press \"O\" : ")
#in case the file doesn't exist, we create one :
with open("data.txt","a") as f:
pass
os.system('clear')
print("* * * QUIZ STARTS! * * *") #this shows the quiz has started after 'o' input
with open("data.txt","r") as f:
question = [line.split(",") for line in f]
i = 0
score = 0 #variables
while i<len(question):
num = random.randint(0,len(question)-1) #creates random question from the list
print("\nQuestion number", i+1,": \nWhat is the translation for", question[num][0], "?")
answer = input("Answer :")
if (answer == str(question[num][1])):
print("Congratulations! That's the good answer!")
score += 1
else:
print("Wrong. The correct answer was :",question[num][1]) #just tells you the wrong answer
i += 1
if len(question)==0:
print("\nThe file is empty. Please add new words to start the quiz !\n")
else:
if i>1:
qu_pl = "questions"
else:
qu_pl = "question"
if score>1:
sc_pl = "answers"
else:
sc_pl = "answer"
print("\n RESULTS :\n ",i, qu_pl,", ",score,"correct ",sc_pl," \n"\
," --> Your score is : ",score*100/i,"% !\n")
The basic concept is that you have a separate file to type in the answers and then the program accesses the separate file and draws information from it.
My problem; the program accesses this file and successfully gains the information but when you actually try to run the program with multiple answers (in my case a 32 answer German Vocab test), the program doesn't mark the answers as right. Have tried many alternatives and it does work with single answers in a .txt document.
If someone has any knowledge and could help me, it would be much appreciated! :)
My .txt questions and answers are set out like this;
beliebt,popular
eng,narrow
Thanks for any help!! <3
The program listed works for me as is (using Python 3.3.2). If you want it to work with multiple possible answers for one word (not sure if that's what you meant), you can use
if (answer in question[num][1:]):
instad of
if (answer == str(question[num][1])):
you might also want to strip any spaces from your sample answers:
for i in range(len(question)):
for j in range(len(question[i])):
question[i][j] = question[i][j].strip(' ')
use lstrip and rstrip if you want to have spaces inside the answer.
Then you can add multiple answers just like this:
What is the translation for eng?
narrow, tight

Resources