Python FileNotFound - python-3.x

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

Related

I'm trying to open file, but I have faced this type of errror FileNotFoundError: [Errno 2] No such file or directory:

how to open file wit python code
#user = ["abcdefghijklmnabcdefghijklww"]
user = open("notes.txt", "r")
print(user.read())
for i in user:
print("The no of occurrences of W is ",i.count("i"))
print("The no of occurrences of i is",i.count("n"))
print("The no of occurrences of s is",i.count("d"))
print("The no of occurrences of e is",i.count("i"))
print("The no of occurrences of n is",i.count("a"))
#print(len(user))
break;
```I'm just trying to open file
```I have tried this methods too
# user = open(r'd:\python\notes.txt')
# print(user)
the error was appered:
Traceback (most recent call last):
File "C:\Users\Pradeep\PycharmProjects\pythonProject\test1.py", line 98, in <module>
user = open("notes.txt", "r")
FileNotFoundError: [Errno 2] No such file or directory: 'notes.txt'
It is possible that you will be able to obtain the desired result by using this piece of code. Check it out. It works for me.
with open('text.txt', 'r') as user_f:
# Read the contents of the file
text = user_f.read()
# Count the occurrence of each letter
W_count = text.count('W')
n_count = text.count('n')
d_count = text.count('d')
i_count = text.count('i')
a_count = text.count('a')
# Print the count for each letter
print(f"The no of occurrences of W is : {W_count}")
print(f"The no of occurrences of n is : {n_count}")
print(f"The no of occurrences of d is : {d_count}")
print(f"The no of occurrences of i is : {i_count}")
print(f"The no of occurrences of a is : {a_count}")

Importing file from path

I am writing a python program that reads from a file 'point.dat' However, when I run the code, I received the error message below.
FileNotFoundError: [Errno 2] No such file or directory: 'points.dat'
May I know what is missing? I tried replacing with the file path but that didn't work as well. any library i need to import in for this to work?
xy=0
xx=0
with open('points.dat') as f:
for line in f:
x,y=[float(p.strip()) for p in line.split(',')]
xy+=x*y
xx+=x*x
k=xy/xx
print('Equation of line y = {:.2f}x'.format(k))
x=input('Enter x coordinate or <ENTER> to end: ')
while x!='':
y=float(input('Enter y coordinate: '))
x=float(x)
if(abs(x*k-y)<1e-2):
print('('+str(x)+',',str(y)+') is on the fitted line')
else:
print('('+str(x)+',', str(y) + ') is not on the fitted line')
x = input('Enter x coordinate or <ENTER> to end: ')
print('End Program')
Can you make sure the extension is correct for the file you are point to? Also have you tried an absolute file path?

I/O operation closed on file in python

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

Word Search Grid code

For the first part of the program i opened a file which is prompted by the user, then wrote code to read, in turn, each line of the file, remove the newline character and append the resulting string to a list of strings.
After the input is complete the grid should be displayed on the screen. But my code is not working according to the instructions, need help please. Below is the code i have done so far:
x = {}
file = input("Enter a filename: ")
try:
a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
a.close()
except IOError as e:
print ("File Does Not Exist")
Not sure what isn't working. You have some unnecessary code. Here is a version that works fine for me:
# x = {}
file = input('enter a filename')
try:
# a = open(file)
with open(file) as a:
x = [line.strip() for line in a]
a.close()
except IOError as e:
print ("File Does Not Exist")
print(x)
Note that i have commented out the unnecessary lines and added a print statement so that you can see the contents of x

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.

Resources