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

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()

Related

Python coinflip code problem: How to delete lines in .text files?

So I'm tring to write a basic coinflip program that I will implement in a web i need the three .text files : heads, crowns and total to keep the overal values. Is there an algorithm or a module that lets u delete the privius content of the file?
(sorry for anything wrong with my question it is my first time asking in stack)
I tried runing the code and it works. My problem is that after it read and tries to write the new number the new number gets writen after the previous one. My only expirience with file handling was in c and in c if u write it makes a new file.
def main():
tot_num = open('total.txt', 'r+')
while True:
try:
x = input('Flip(F) or Exit(E)').lower()
except ValueError:
print('You had ur options try again')
else:
if x == 'f' or x == 'flip':
cf = coin_flip()
if cf == 'head':
print('Coin --> HEAD')
heads = open('heads.txt', 'r+')
h_num = int(heads.read())
heads.write(f'{h_num + 1}')
tn = int(tot_num.read())
tot_num.write(f'{tn + 1}')
heads.close()
show_coin_flip_num()
elif cf == 'crown':
print('Coin --> CROWN')
crowns = open('crown.txt', 'r+')
c_num = int(crowns.read())
crowns.write(f'{c_num + 1}')
tn = int(tot_num.read())
tot_num.write(f'{tn + 1}')
crowns.close()
show_coin_flip_num()
else:
break
else:
print('Exiting...')
break
The error is basically there cuz after the new number is added it goes next to the previous one it can read it normally the next time. It takes '012'
from the file.
Traceback (most recent call last):
File "file_path", line 462, in <module>
main()
File "file_path", line 442, in main
tn = int(tot_num.read())
ValueError: invalid literal for int() with base 10: ''
I made my program work but it is peculiar that there is not function to delete a specific line from file. I will try to make one myself and post it here because all the answers in
https://stackoverflow.com/q/4710067/7987118 are used to remove specific strings from a text file.

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.)

Python 3.6.1: Code does not execute after a for loop

I've been learning Python and I wanted to write a script to count the number of characters in a text and calculate their relative frequencies. But first, I wanted to know the length of the file. My intention is that, while the script goes from line to line counting all the characters, it would print the current line and the total number of lines, so I could know how much it is going to take.
I executed a simple for loop to count the number of lines, and then another for loop to count the characters and put them in a dictionary. However, when I run the script with the first for loop, it stops early. It doesn't even go into the second for loop as far as I know. If I remove this loop, the rest of the code goes on fine. What is causing this?
Excuse my code. It's rudimentary, but I'm proud of it.
My code:
import string
fname = input ('Enter a file name: ')
try:
fhand = open(fname)
except:
print ('Cannot open file.')
quit()
#Problematic bit. If this part is present, the script ends abruptly.
#filelength = 0
#for lines in fhand:
# filelength = filelength + 1
counts = dict()
currentline = 1
for line in fhand:
if len(line) == 0: continue
line = line.translate(str.maketrans('','',string.punctuation))
line = line.translate(str.maketrans('','',string.digits))
line = line.translate(str.maketrans('','',string.whitespace))
line = line.translate(str.maketrans('','',""" '"’‘“” """))
line = line.lower()
index = 0
while index < len(line):
if line[index] not in counts:
counts[line[index]] = 1
else:
counts[line[index]] += 1
index += 1
print('Currently at line: ', currentline, 'of', filelength)
currentline += 1
listtosort = list()
totalcount = 0
for (char, number) in list(counts.items()):
listtosort.append((number,char))
totalcount = totalcount + number
listtosort.sort(reverse=True)
for (number, char) in listtosort:
frequency = number/totalcount*100
print ('Character: %s, count: %d, Frequency: %g' % (char, number, frequency))
It looks fine the way you are doing it, however to simulate your problem, I downloaded and saved a Guttenberg text book. It's a unicode issue. Two ways to resolve it. Open it as a binary file or add the encoding. As it's text, I'd go the utf-8 option.
I'd also suggest you code it differently, below is the basic structure that closes the file after opening it.
filename = "GutenbergBook.txt"
try:
#fhand = open(filename, 'rb')
#open read only and utf-8 encoding
fhand = open(filename, 'r', encoding = 'utf-8')
except IOError:
print("couldn't find the file")
else:
try:
for line in fhand:
#put your code here
print(line)
except:
print("Error reading the file")
finally:
fhand.close()
For the op, this is a specific occasion. However, for visitors, if your code below the for state does not execute, it is not a python built-in issue, most likely to be: an exception error handling in parent caller.
Your iteration is inside a function, which is called inside a try except block of caller, then if any error occur during the loop, it will get escaped.
This issue can be hard to find, especially when you dealing with intricate architecture.

How do you report duplicates in a txt. file?

In our class we were given the task to basically create a program that re-enacts the US election last year. One of the extra challenges is that when you enter an ID number that is already in the file, it should come up with an error and just stop. However, when I try to execute this code, it comes up with
ValueError: I/O operation on closed file.
This is the code I've done so far...
ID = input("Please input ID code ")
if(len(ID)) == 6:
print("ID length: Valid")
N += 1
else:
print("ID Code: Error")
sys.exit()
with open('ID.txt', 'a') as idc:
idc.write(ID + ' ')
already_seen = set()
for line in idc:
if line not in already_seen:
print("Valid")
else:
print("Error")
sys.exit()
Thanks
You should know the difference between the
with open('ID.txt', 'a') as idc:
do sth
and the
idc = open('ID.txt', 'a')
In the first case, after the do sth finished, the __exit__() of the idc will be called to close the file object.
I advise you to use the second expression that I indicate above. If you are new to Python, this blog will help you to understand the detail reasons.

Resources