How do you report duplicates in a txt. file? - python-3.x

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.

Related

Word "None" on line below input [duplicate]

This question already has answers here:
Why does my input always display none in python? [closed]
(2 answers)
Closed 23 days ago.
I wrote a simple program to track household items and output to a text file, with a while loop to have it keep running till "exit" is entered. I get the word "None" on the line below the input line when I haven't written it to do so. Here is my code.
HouseHoldItems = open('C:\\_PythonClass\\Assignment03\\HouseHoldItemsAndValue.txt', mode='a')
Items = ''
Value = ''
# while loop to keep program running until user enters "Exit"
while(True):
# Items is the primary variable, determines if user is entering new household item or wants to end the program
Items = input(print("Enter an Item (Or type 'Exit' to quit) : "))
# If statement to determine if user wants to end program
if(Items.lower() == "exit"):
break
# Else statement to write household items to the file, followed by value of items
else:
HouseHoldItems.write(Items + ', ')
Value = input(print("Enter an estimated Value: "))
HouseHoldItems.write(Value + '\n')
HouseHoldItems.close()
Here is a snip of the way the code looks as I input data items. (https://i.stack.imgur.com/CHOWk.png)
Is it part of the while(true) piece that is making it do this? Thanks for the help in advance.
You do not need to use the print function when using the input function.
Use:
Items = input("Enter an Item (Or type 'Exit' to quit) : ")
and:
Value = input("Enter an estimated Value: ")
While we're at it, in test conditions for while and if statements while your code works as is, it is not considered 'pythonic'. The pythonic way is to not use parentheses. ie
While True:
and:
if Items.lower() == "exit":

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

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.

Only read first line of a text file

I have a text file named "paintingJobs". The data looks like this:
E5341,21/09/2015,C102,440,E,0
E5342,21/09/2015,C103,290,A,290
E5343,21/09/2015,C104,730,N,0
E5344,22/09/2015,C105,180,A,180
I have written a program that only finds the first entry but cannot find any data beyond the first line (I think it is to do with Python including /n in front of the username) The program looks like this.
def ASearch():
print("Option A: Search for an estimate")
print("Please enter the estimate number: ")
estimateNumber = str(input())
file = open("paintingJobs.txt", "r")
paintJobs = file.readlines()
file.close()
length = len(paintJobs)
paintData = []
for line in paintJobs:
estNumber, estDate, CustID, FinalTotal, Status, AmountPaid = line.split(",")
if estimateNumber == estNumber:
print("Estimate number: ", estNumber)
print("Customer ID: ", CustID)
options()#this is a function in a for a different part of the program that works fine
else:
print("You have entered an incorrect estimate number; please try again")
ASearch()
How do I get the program to read (and return the values of) the second entry in the list E.G. E5342 (any help would be appreciated greatly)

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

Resources