I/O operation closed on file in python - python-3.x

I have to write a program that prompts the user to enter six test names and their scores and writes them to a text file named tests.txt. You must use a loop. Each input should be written to its own line in the file. The program should generate a confirmation message when done. When I run my program it works but then I get an error at the end saying:
Traceback (most recent call last):
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 34, in <module>
main()
File "C:/Users/brittmoe09/Desktop/program6_1.py", line 18, in main
test_scores.write(name + '\n')
ValueError: I/O operation on closed file.
I am not sure what I am doing wrong, any help would be appreciated.
Here is my code:
def main():
test_scores = open('tests.txt', 'w')
print('Entering six tests and scores')
for count in range(6):
name = input('Enter a test name')
score = int(input('Enter % score on this test'))
while name != '':
test_scores.write(name + '\n')
test_scores.write(str(score) + '\n')
test_scores.close()
print('File was created successfully')
main()

Here's what I did. Get rid of that 2nd while loop, and move the close file out of the for loop because you are closing the file in the loop which is giving you the error: (some of my variable names are different than yours so look out for that)
test_scores = open('tests.txt','w')#open txt file
print('Entering six tests and scores')
for count in range(6):#for loop to ask the user 6 times
name = input('Enter a test name: ')
testscore = int(input('Enter % score on this test: '))
for count2 in range(1):
test_scores.write(str(name) + '\n')
test_scores.write(str(testscore) + '\n')
test_scores.close()#close the txt file
print('File was created successfully!')

the block while:
while name != '':
...
This is an infinity loop if your "name" != '', so in first loop the file closed and second loop you get an error

Related

File Handling errors in the following code

Is anyone able to trouble shoot and provide an explanation for the following apparent file handling errors in this code:
Full Code listing on Trinket
https://trinket.io/python/075581aa4f
Using the following test data:
Type in a number (1-7): 2
Add Name and Number
Name: misscomputing
Number: 07373747273
Type in a number (1-7): 6
Filename to save: numbers.txt
The following error results:
IOError: File not open for writing on line 74 in main.py
Furthermore, option 5 which is loading the file does not work either.
Type in a number (1-7): 2
Add Name and Number
Name: misscomputing
Number: 03030483
Type in a number (1-7): 5
Filename to load: numbers.txt
Error
ValueError: need more than 1 values to unpack on line 71 in main.py
The two relevant functions are:
def load_numbers(numbers, filename):
in_file = open(filename, "rt")
while True:
in_line = in_file.readline()
if not in_line:
break
in_line = in_line[:-1]
name, number = in_line.split(",")
numbers[name] = number
in_file.close()
def save_numbers(numbers, filename):
out_file = open(filename, "wt")
for k, v in numbers.items():
out_file.write(k + "," + v + "\n")
out_file.close()
..but as mentioned the full code listing is here: https://trinket.io/python/075581aa4f
The examples are taken from the tutorial on https://en.wikibooks.org

Factorial of a given number using sequential program

I am new to this python coding.So,please can someone find what is the problem with this code.
def factorial(n):
sum=1
for i in range(1..n+1):
sum=sum*i
print(sum)
return sum
v=int(input("enter the number:"))
factorial(v)
the error i get:
enter the number:4
Traceback (most recent call last):
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py",line 9, in <module>
factorial(v)
File "C:/Users/Ramakrishnar/AppData/Local/Programs/Python/Python36/fact.py", line 3, in factorial
for i in range(1..n+1):
AttributeError: 'float' object has no attribute 'n'
There are two ways you can write your program. To reformat your code so that it is in good form, you might organize your program like so:
def main():
variable = int(input('Enter the number: '))
print(factorial(variable))
def factorial(number):
total = 1
for integer in range(1, number + 1):
total *= integer
return total
if __name__ == '__main__':
main()
If instead you are trying to accomplish the same thing using the least amount of code, the following two lines will do the exact same thing for you:
import math
print(math.factorial(int(input('Enter the number: '))))

ZipFile cracker works with a few combinations and crashes when many combinations are used

I've found many examples of zip crackers written in python, but unfortunatelly they were either written in python2 or have the functionality I do not need (i.e. use of dictionaries saved in files). For me was interesting to check how long and how much memory will it take to break, let's say, a password of 5-10 different symbols (a-z, a-zA-Z, a-zA-Z1-10 etc.). Afterwards I can try different libraries and techniques (threads etc.) to improve performance of the code and, hopefully, get better undestaning of python mechanics in the process.
Here is my program. It works well when the program tries 2-position passwords (a-zA-Z) and crashes with longer passwords.
import os
import shutil
import zipfile
from itertools import permutations, combinations_with_replacement
from string import ascii_letters
#passgen() yields passwords to be checked
def passgen(passminlength, passmaxlength,searchdict):
prevpwd = []
for n in range(passminlength,passmaxlength):
for p in combinations_with_replacement(searchdict,n):
for k in permutations(p,n):
pwd_tmp=''.join(k)
if prevpwd != pwd_tmp: #without this check passgen() yields
prevpwd = pwd_tmp #recurring password combinations
yield pwd_tmp #due to the logic behind permutations()
if __name__ == '__main__':
zFile = zipfile.ZipFile("secret.zip", 'r') #encrypted file to crack
pwd = None #password to find
output_directory = os.path.curdir+"/unzip_tmp" #output tmpfolder for extracted files
if not os.path.isdir(output_directory): #if it exists - delete, otherwise - create
os.makedirs('unzip_tmp')
else:
shutil.rmtree(output_directory)
os.makedirs('unzip_tmp')
searchdict = list(ascii_letters) #list with symbols for brute force: a-zA-Z
passminlength = 1
passmaxlength = 3 #code works with passmaxlength=2, doesn't - with passmaxlength=3
pwd_tmp = passgen(passminlength,passmaxlength,searchdict) #pwd_tmp is an iterator
while True:
try:
tmp = next(pwd_tmp)
except StopIteration: #iterator is empty-> quit while-loop
break
print("trying..:%s" % tmp)
zFile.setpassword(bytes(tmp,'ascii'))
try:
zFile.extractall(output_directory)
pwd = tmp
break #password is found->quit while-loop
except RuntimeError: #checked password is wrong ->go again though while loop
print("wrong password:%s" % tmp)
print("password is:%s" % pwd)
The program crashes with maxpasslength=3 on the row with "zFile.extractall(output_directory)".
Error is:
Traceback (most recent call last):
File "C:\Experiments\Eclipse\Workspace\messingaroundpython\zipcracker.py", lin
e 48, in <module>
zFile.extractall(output_directory)
File "C:\Python34\lib\zipfile.py", line 1240, in extractall
self.extract(zipinfo, path, pwd)
File "C:\Python34\lib\zipfile.py", line 1228, in extract
return self._extract_member(member, path, pwd)
File "C:\Python34\lib\zipfile.py", line 1292, in _extract_member
shutil.copyfileobj(source, target)
File "C:\Python34\lib\shutil.py", line 67, in copyfileobj
buf = fsrc.read(length)
File "C:\Python34\lib\zipfile.py", line 763, in read
data = self._read1(n)
File "C:\Python34\lib\zipfile.py", line 839, in _read1
data = self._decompressor.decompress(data, n)
zlib.error: Error -3 while decompressing data: invalid distance too far back
I am stuck. Any idea what I could be missing?
Update: It seems to be a bug from zlib. I added an exeption catcher to ignore bad combinations:
except RuntimeError: #checked password is wrong ->go again though while loop
print("wrong password:%s" % tmp)
except Exception as err:
print("zlib bug, wrong password?:%s" % tmp)
Now the program can process much longer passwords.

Python 3: Checking for the length and data type. & Error Fix

I am having some problems with my project:
With the code I currently have, I am getting an error:
Traceback (most recent call last):
File "\Username\Folder\Folder2\design2.py", line 13, in <module>
elif numberplate3.isaplha():
AttributeError: 'str' object has no attribute 'isaplha'
Here is the code:
while True:
import time
numberplate1 = str(input("Enter in the first 2 letters of the numberplate"))
if numberplate1.isalpha():
print("Verification 1 Success")
numberplate2 = str(input("Enter in the next 2 chars of the numberplate"))
if numberplate2.isdigit():
print("Verification 2 Success")
numberplate3 = str(input("Enter the last 3 digits of the numberplate"))
if numberplate3.isdigit():
print("Verification 3 Fail")
break
elif numberplate3.isaplha():
print("Verification Passed")
start
elif numberplate2.isalpha():
print("Verification 2 Failed")
break
elif numberplate1.isdigit():
print("Return to the start")
break
start = time.time()
inp = input("Please press enter when car has left monitoring area\n>")
end = time.time()
print("Car took {:.2f} seconds ".format(end-start))
print("Car travelled at {:.2f} m/s. ".format(200/(end-start)))
The program will check the format of a numberplate, but I would also like for it to check for the length too. (It checks to see if it has a letter, number etc, but it needs to check for the length on each check)
If possible, a program that checks for the numberplate format would really help.
Checking for LETTER-LETTER-NUMBER-NUMBER LETTER-LETTER-LETTER (AB12 CDE) If not, I am fine with help on my current program
Thanks
Your first problem is just a typo: You misspelled 'isaplha'; it should be 'isalpha'.
For your other question: You can make your program a whole lot simpler by using a regular expression for matching the number plate, like this:
import re
while True:
numberplate = input("Enter the numberplate: ").lower()
if re.match("[a-z]{2}[0-9]{2}[a-z]{3}", numberplate):
print("Verification Success")
break
else:
print("Verification Failed")
Here, the regular expression "[a-z]{2}[0-9]{2}[a-z]{3}" means "two letters, two digits, three letters".

Python FileNotFound

I am fairly new to python.
I am trying to make a script that will read sudoku solutions and determent if they are correct or not.
Things I need:
1] Prompt the user to enter a file/file path which includes the sudoku numbers. Its a .txt file of 9 rows and columns. Consist only of numbers.
2] Have some kind of an error handling.
3] Then, if the sudoku is valid, i should create a new text file using the same format as the original input file with the prefix "Correct_"
I have not fully finished the program, but I get this error when I put a false path or file name.
Hello to Sudoku valitator,
Please type in the path to your file and press 'Enter': example.txt #This is a non existing file, to test the Error Exception
'Traceback (most recent call last):
File "C:/Users/FEDROS/Desktop/bs.py", line 9, in <module>
sudoku = open(prompt, 'r').readlines()
FileNotFoundError: [Errno 2] No such file or directory: 'example.txt'
Here is my script:
while True:
try:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
break
except (FileNotFoundError, IOError):
print("Wrong file or file path")
sudoku = open(prompt, 'r').readlines()
def check(game):
n = len(game)
if n < (1):
return False
for i in range(0, n):
horizontal = []
vertical = []
for k in range(0, n):
if game[k][i] in vertical:
return ("File checked for errors. Your options are wrong!")
vertical.append(game[k][i])
if game[i][k] in horizontal:
return ("File checked for errors. Your options are wrong!")
horizontal.append(game[i][k])
return ("File checked for errors. Your options are correct!")
print (check(sudoku))
Thanks, any advice or help will be appreciated.
try block should be around open. Not around prompt.
while True:
prompt = input("\n Hello to Sudoku valitator,"
"\n \n Please type in the path to your file and press 'Enter': ")
try:
sudoku = open(prompt, 'r').readlines()
except FileNotFoundError:
print("Wrong file or file path")
else:
break
You can try adding this code before open() function:
import os
pathname = __file__
os.chdir(os.path.dirname(pathname))

Resources