I have this code that creates unique passwords using the first letter of each word from the file.Before each password is created(written to a file) it is compared to all passwords that are currently in the file, so if the file has 50,000 passwords before a another is written it has to scan through all 50k.
A user can input any amount of passwords needed but the bigger the number the longer it takes 100k will take a long time how can i optimize this to make the program run faster ? The password generation is not included code
for mainLoop in range(passnum):
user = 0
newpass = generatePassword() # New password generated each iteration of loop
storePass = open("MnemPass.txt","a")
print ("PASSWORD GENERATED ")
#Checks if file is empty if True write first password
fileEmpty = os.stat("MnemPass.txt").st_size == 0
if fileEmpty == True:
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("FIRST PASSWORD WRITTEN")
#IF file is not empty Read line by line and compare each with new password generated returns boolean value
elif fileEmpty == False:
storePass = open("MnemPass.txt","r")
with open("MnemPass.txt") as f:
fileData = f.read().splitlines()
linelength = len(fileData).__int__()
filemax = linelength
num = linelength #Number used to cycle through array set to size of list
#print(linelength+10)
for iterate in range(linelength):
num = num - 1 #Number decreases each pass
#print num
if fileData[num] != newpass: # The last element in the array is checked first decrementing each pass
go = True
if fileData[num]==newpass: #changed
print ("match found: PASSWORD : "+fileData[num])
passMatch = open("Matchpassword.txt","a")
passMatch.write(newpass)
passMatch.write("\n")
passMatch.close()
go = False
break
#places new password once it does not match and all elements prev passwords are compared
if go == True and num == 0:
storePass = open("MnemPass.txt","a")
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("NEW WRITTEN")
if linelength == filemax:
num = num -1
*new Code - i used the set function *
passnum = (input("How many passwords do you need :"))
sTime = datetime.now()
storePass = open ("MnemPass.txt","a") # file open out of loop to increase speed
fileEmpty = os.stat("MnemPass.txt").st_size == 0
new_passwords = set()
CurrentPasswords = set()
if fileEmpty == True:
while len(new_passwords)!= passnum: #will cause problems if dictionary cannot create amount needed
new_passwords.add(generatePassword())
for pw in new_passwords:
storePass.write(pw + "\n")
else:
new_passwords = set(line.strip() for line in open ("MnemPass.txt"))
for num in range(passnum):
temp = generatePassword()
if temp not in new_passwords:
CurrentPasswords.add(temp)
else:
"match found"
for pw2 in CurrentPasswords:
storePass.write(pw2 + "\n")
You can considerably reduce runtime by loading the file once and then appending each new password to it rather than open file in loop and check line by line,Here I am using uuid in generatePassword() to generate a random string of length between 3 and 10
Your code:
def func(passnum):
import os,uuid,random
def generatePassword():
return str(uuid.uuid4()).replace('-', '')[0:random.randint(3,10)]
for mainLoop in range(passnum):
user = 0
newpass = generatePassword() # New password generated each iteration of loop
storePass = open("MnemPass.txt","a")
print ("PASSWORD GENERATED ")
#Checks if file is empty if True write first password
fileEmpty = os.stat("MnemPass.txt").st_size == 0
if fileEmpty == True:
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("FIRST PASSWORD WRITTEN")
#IF file is not empty Read line by line and compare each with new password generated returns boolean value
elif fileEmpty == False:
storePass = open("MnemPass.txt","r")
with open("MnemPass.txt") as f:
fileData = f.read().splitlines()
linelength = len(fileData).__int__()
filemax = linelength
num = linelength #Number used to cycle through array set to size of list
#print(linelength+10)
for iterate in range(linelength):
num = num - 1 #Number decreases each pass
#print num
if fileData[num] != newpass: # The last element in the array is checked first decrementing each pass
go = True
if fileData[num]==newpass: #changed
print ("match found: PASSWORD : "+fileData[num])
passMatch = open("Matchpassword.txt","a")
passMatch.write(newpass)
passMatch.write("\n")
passMatch.close()
go = False
break
#places new password once it does not match and all elements prev passwords are compared
if go == True and num == 0:
storePass = open("MnemPass.txt","a")
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("NEW WRITTEN")
if linelength == filemax:
num = num -1
I slightly modified it to load the file at starting itself and append for every new password, notice that we don't need inner for loop anymore, the code becomes:
def func2(passnum):
import uuid
import os, random
linelength = 0
fileData = []
if os.path.isfile('MnemPass.txt'):
f = open("MnemPass.txt", "r")
fileData += f.read().splitlines()
linelength = len(fileData).__int__()
f.close()
def generatePassword():
return str(uuid.uuid4()).replace('-', '')[0:random.randint(3,10)]
for mainLoop in range(passnum):
user = 0
newpass = generatePassword() # New password generated each iteration of loop
storePass = open("MnemPass.txt", "a")
print ("PASSWORD GENERATED ")
# Checks if file is empty if True write first password
fileEmpty = os.stat("MnemPass.txt").st_size == 0
if fileEmpty == True:
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("FIRST PASSWORD WRITTEN")
# IF file is not empty Read line by line and compare each with new password generated returns boolean value
elif fileEmpty == False:
storePass = open("MnemPass.txt", "r")
filemax = linelength
num = linelength # Number used to cycle through array set to size of list
# print(linelength+10)
if newpass in fileData:
print ("match found: PASSWORD : " , fileData.index(newpass))
passMatch = open("Matchpassword.txt", "a")
passMatch.write(newpass)
passMatch.write("\n")
passMatch.close()
else:
linelength += 1
fileData.append(newpass)
storePass = open("MnemPass.txt", "a")
storePass.write(newpass)
storePass.write("\n")
storePass.close()
print ("NEW WRITTEN")
if linelength == filemax:
num = num - 1
Profile for your code:
Profile for modified code:
As you can see the runtime has reduced from 45secs to 27secs ! :)
NOTE:
I ran the tests for 10000 passwords and deleted the generated files for next pass :)
In the case that your code runs in a loop as you present here:
Checking the whole file on every loop iteration is not very efficient.
It is much more efficient to keep a set of created passwords and check if a new password is already in the set before adding it.
Also in this case you should only open the file once outside the main for loop and close it afterwards.
In the case that your program adds only one password and then returns, it is better to add each new password in a way that your file remains sorted. This way you can use binary search to search if a password already exists.
Related
This is the code to search a particular entry in a file:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
num = "0"
flag = False
while (num != ""):
num = test_file.readline()
if (num == num2find):
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The test file is:
1
2
3
4
5
If I input 2, the code still outputs "Number not found."
Every time you read a line from a text file, you are getting "\n" at the end of the string line, so the problem you are facing is that you are comparing "2" to "2\n" which is not the same.
You could take advantage of with to pen your file. This way you do not need to worry about closing the file once you are done with it. Also, you do not need to pass the "r" argument since it is the default mode for open.
You should use a for loop instead of that needless while loop. The for loop will terminate automatically when all the lines in the file have been read.
One more improvement you could make is to rename the flag flag to found, and to print the result once the file has been processed.
num2find = int(input("Enter a number to find: "))
found = False # rename flag
with open("testfile.txt") as test_file: # use with to avoid missing closing the file
for line in test_file: # use a for loop to iterate over each line in the file
num = int(line)
if num == num2find:
found = True
break
if found: # print results at the end once file was processed
print("Number found.")
else:
print("Number not found.")
Each line in the test file contains two characters - the number and a newline. Since "2" does not equal "2\n", your number is not being found. To fix this, use the int function to parse your lines, since it ignores whitespace (like the \n) character:
num2find = int(input("Enter a number to find: "))
flag = False
with open("testfile.txt", "r") as test_file:
for line in test_file:
num = int(line)
if num == num2find:
print("Number found.")
flag = True
break
if not flag:
print("\nNumber not found.")
The easiest and the most logical solution I could come up with after all the feedback was this:
num2find = int(input("Enter a number to find: "))
file_data = open("testfile.txt", "r")
found = False
for data in file_data:
if int(data) == num2find:
found = True
if found:
print("\nNumber found.")
else:
print("\nNumber not found.")
file_data.close()
You need to add .rstrip() on num = test_file.readline()
Try something like this:
num2find = str(input("Enter a number to find: "))
test_file = open("testfile.txt", "r")
file_data = test_file.readlines()
flag = False
for item in file_data:
if num2find == item.rstrip():
flag = True
break
if not flag:
print("\nNumber not found.")
else:
print("Number found")
Don't use .readline() like that, use readlines() instead
I have created a program where I have two text files: "places.txt" and "verbs.txt" and It asks the user to choose between these two files. After they've chosen it quizzes the user on the English translation from the Spanish word and returns the correct answer once the user has completed their "test". However the program runs smoothly if the text files are free in the folder for python I have created on my Mac but once I put these files and the .py file in a subfolder it says files can't be found. I want to share this .py file along with the text files but would there be a way I can fix this error?
def CreateQuiz(i):
# here i'm creating the keys and values of the "flashcards"
f = open(fileList[i],'r') # using the read function for both files
EngSpanVocab= {} # this converts the lists in the text files to dictionaries
for line in f:
#here this trims the empty lines in the text files
line = line.strip().split(':')
engWord = line[0]
spanWord = line[1].split(',')
EngSpanVocab[engWord] = spanWord
placeList = list(EngSpanVocab.keys())
while True:
num = input('How many words in your quiz? ==>')
try:
num = int(num)
if num <= 0 or num >= 10:
print('Number must be greater than zero and less than or equal to 10')
else:
correct = 0
#this takes the user input
for j in range(num):
val = random.choice(placeList)
spa = input('Enter a valid spanish phrase for '+val+'\n'+'==> ')
if spa in EngSpanVocab[val]:
correct = correct+1
if len(EngSpanVocab[val]) == 1:
#if answers are correct the program returns value
print('Correct. Good work\n')
else:
data = EngSpanVocab[val].copy()
data.remove(spa)
print('Correct. You could also have chosen',*data,'\n')
else:
print('Incorrect, right answer was',*EngSpanVocab[val])
#gives back the user answer as a percentage right out of a 100%
prob = round((correct/num)*100,2)
print('\nYou got '+str(correct)+' out of '+str(num)+', which is '+str(prob)+'%'+'\n')
break
except:
print('You must enter an integer')
def write(wrongDict, targetFile):
# Open
writeFile = open(targetFile, 'w')
# Write entry
for key in wrongDict.keys():
## Key
writeFile.write(key)
writeFile.write(':')
## Value(s)
for value in wrongDict[key]:
# If key has multiple values or user chooses more than 1 word to be quizzed on
if value == wrongDict[key][(len(wrongDict[key])) - 1]:
writeFile.write(value)
else:
writeFile.write('%s,'%value)
writeFile.write('\n')
# Close
writeFile.close()
print ('Incorrect answers written to',targetFile,'.')
def writewrong(wringDict):
#this is for the file that will be written in
string_1= input("Filename (defaults to \'wrong.txt\'):")
if string_1== ' ':
target_file='wrong.txt'
else:
target_file= string_1
# this checs if it already exists and if it does then it overwrites what was on it previously
if os.path.isfile(target)==True:
while True:
string_2=input("File already exists. Overwrite? (Yes or No):")
if string_2== ' ':
write(wrongDict, target_file)
break
else:
over_list=[]
for i in string_1:
if i.isalpha(): ovrList.append(i)
ovr = ''.join(ovrList)
ovr = ovr.lower()
if ovr.isalpha() == True:
#### Evaluate answer
if ovr[0] == 'y':
write(wrongDict, target)
break
elif ovr[0] == 'n':
break
else:
print ('Invalid input.\n')
### If not, create
else:
write(wrongDict, target)
def MainMenu():
## # this is just the standad menu when you first run the program
if len(fileList) == 0:
print('Error! No file found')
else:
print( "Vocabulary Program:\nChoose a file with the proper number or press Q to quit" )
print(str(1) ,"Places.txt")
print(str(2) ,"Verbs.txt")
while True:
#this takes the user input given and opens up the right text file depending on what the user wants
MainMenu()
userChoice = input('==> ')
if userChoice == '1':
data = open("places.txt",'r')
CreateQuiz(0)
elif userChoice == '2':
data = open("verbs.txt",'r')
CreateQuiz(1)
elif userChoice == 'Q':
break
else:
print('Choose a Valid Option!!\n')
break
You are probably not running the script from within the new folder, so it tries to load the files from the directory from where you run the script.
Try setting the directory:
import os
directory = os.path.dirname(os.path.abspath(__file__))
data = open(directory + "/places.txt",'r')
I want to be able to have a program whereby the user can input a paragraph/sentence/word/character whatever and have that stored in a list e.g. in list[0]. Then I want them to be able to write another bit of text and have that stored in e.g. list[1]. Then at any time I want the user to be able to read that from the list by choosing which segment they want to read from e.g. reading "hello" from list[0] whilst in list[1] "hi" is stored. Then when the user exits the program I want the list to be written to an external file. Then, at next start up, the program should read the file contents and store it again in the list so that the user can add more bits of text or read the current bits. When the list is saved to a file it should append new or changed parts but overwrite parts that are the same so as not to have duplicates. I have attempted this without much success. I am to be honest not sure if it is possible. I have browsed similar forums and have found that hasn't helped much so here it is.
My code so far:
import os
import time
import csv
global write_list
global f1_contents
write_list = []
def write():
os.system("cls")
user_story = input("Enter your text: \n")
write_list.append(user_story)
def read():
os.system("cls")
user_select_needs = True
while user_select_needs == True:
user_select = input("Enter the list section to read from or type exit: \n")
if user_select == "exit":
user_select_needs = False
try:
int(user_select)
select = user_select
select = int(select)
try:
print(write_list[select])
user_select_needs = False
enter = input("Press enter:")
except:
print("There is not stored data on that section!")
except ValueError:
print("That is not a valid section!")
def exit():
os.system("cls")
max_num_needs = True
while max_num_needs == True:
set_max_num = input("Set the storage: \n")
try:
int(set_max_num)
max_num = set_max_num
max_num = int(max_num)
max_num_needs = False
except:
print("It must be an integer!")
for i in range(0, max_num):
f = open("Saves.txt", "a")
f.write(write_list[i])
f.close()
os._exit(1)
def main():
store_num_needs = True
while store_num_needs == True:
set_store_num = input("State the current storage amount: \n")
try:
int(set_store_num)
store_num = set_store_num
store_num = int(store_num)
store_num_needs = False
except:
print("It must be an integer!")
try:
f1 = open("Saves.txt", "r")
for i in range(0, store_num+1):
i, = f1.split("#")
f1.close()
except:
print("--------Loading-------")
time.sleep(1)
while True:
os.system("cls")
user_choice = ""
print("Main Menu" + "\n" + "---------")
print("1) Write")
print("2) Read")
print("3) Exit")
while user_choice not in ["1", "2", "3"]:
user_choice = input("Pick 1, 2 or 3 \n")
if user_choice == "1":
write()
elif user_choice == "2":
read()
else:
exit()
if __name__ == "__main__":
main()
It might be too complicated to understand in which case just ask me in comments- otherwise general tips would be nice aswell.
Thanks in advance
A quick point of correction:
global is only required if you're defining a global variable inside a non-global context. In other words, anything defined at the default indentation level, will be accessible by everything else defined below it. For example:
def set_global():
x = 1
def use_global():
x += 1
set_global()
try:
use_global()
except Exception as e:
# `use_global` doesn't know
# about what `set_global` did
print("ERROR: " + str(e))
# to resolve this we can set `x` to a
# default value in a global context:
x = 1
# or, if it were required, we
# could create a global variable
def make_global():
global x
make_global()
# either will work fine
set_global()
use_global()
print(x) # prints 2
Now to the actual question:
I haven't read through the block of code you wrote (probably best to trim it down to just the relevant bits in the future), but this should solve the problem as I understand it, and you described it.
import os
import sys
user_text = []
# login the user somehow
user_file = 'saves.txt'
def writelines(f, lines):
"""Write lines to file with new line characters"""
f.writelines('\n'.join(lines))
def readlines(f):
"""Get lines from file split on new line characters"""
text = f.read()
return text.split('\n') if text else []
class _Choice(object):
"""Class that is equivalent to a set of choices
Example:
>>> class YesObj(Choice):
>>> options = ('y', 'yes')
>>> Yes = YesObj()
>>> assert Yes == 'yes'
>>> assert Yes == 'y'
>>> # assertions evaluate to True
Override the `options` attribute to make use
"""
allowed = ()
def __eq__(self, other):
try:
s = str(other)
except:
raise TypeError("Cannot compare with non-string")
else:
return s.lower() in self.allowed
def _choice_repr(choices):
allowed = []
for c in choices:
if isinstance(c, _Choice):
allowed.extend(c.allowed)
else:
allowed.append(c)
if len(allowed) > 2:
s = ', '.join([repr(c) for c in allowed[:-1]])
s += ', or %s' % repr(allowed[-1])
elif len(allowed) == 1:
s = '%s or %s' % allowed
else:
s = '%s' % allowed[0]
return s
def _choice_sentinel(name, allowed):
"""Creates a sentinel for comparing options"""
return type(name, (_Choice,), {'allowed': list(allowed)})()
Quit = _choice_sentinel('Quit', ('q', 'quit'))
Yes = _choice_sentinel('Yes', ('y', 'yes'))
No = _choice_sentinel('No', ('n', 'no'))
def readline_generator(f):
"""Generate a file's lines one at a time"""
t = f.readline()
# while the line isn't empty
while bool(t):
yield t
t = f.readline()
def read_from_cache():
"""Overwrite `user_text` with file content"""
if not os.path.isfile(user_file):
open(user_file, 'w').close()
globals()['user_text'] = []
else:
with open(user_file, 'r') as f:
lines = readlines(f)
# replace vs extend user text
for i, t in enumerate(lines):
if i == len(user_text):
user_text.extend(lines[i:])
else:
user_text[i] = t
def write_to_cache():
"""Overwrite cache after the first line disagrees with current text
If modifications have been made near the end of the file, this will
be more efficient than a blindly overwriting the cache."""
with open(user_file, 'r+') as f:
i = -1
last_pos = f.tell()
# enumerate is a generator, not complete list
for i, t in enumerate(readline_generator(f)):
if user_text[i] != t:
# rewind to the line before
# this diff was encountered
f.seek(last_pos)
# set the index back one in
# order to catch the change
i -= 1
break
last_pos = f.tell()
# then cut off remainder of file
f.truncate()
# recall that i is the index of the diff
# replace the rest of it with new
# (and potentially old) content
writelines(f, user_text[i+1:])
def blind_write_to_cache():
"""Blindly overwrite the cache with current text"""
with open(user_file, 'w') as f:
writelines(f, user_text)
def overwrite_user_text(i, text, save=False):
"""Overwrite a line of text
If `save` is True, then these changes are cached
"""
try:
user_text[i] = text
except IndexError:
raise IndexError("No text exists on line %r" % (i+1))
if save:
write_to_cache()
def user_input():
"""Get a new line from the user"""
return raw_input("input text: ")
def user_choice(msg, choices):
if len(choices) == 0:
raise ValueError("No choices were given")
ans = raw_input(msg)
if ans not in choices:
print("Invalid Response: '%s'" % ans)
m = "Respond with %s: " % _choice_repr(choices)
return user_choice(m, choices)
else:
return ans
def user_appends():
"""User adds a new line"""
user_text.append(user_input())
def user_reads(*args, **kwargs):
"""Print a set of lines for the user
Selects text via `user_text[slice(*args)]`
Use 'print_init' in kwargs to choose how
many lines are printed out before user must
scroll by pressing enter, or quit with 'q'."""
print_init = kwargs.get('print_init', 4)
sliced = user_text[slice(*args)]
if not isinstance(sliced, list):
sliced = [sliced]
for i, l in enumerate(sliced):
if i < print_init:
print(l)
sys.stdout.flush()
elif user_choice(l, ['', Quit]) == Quit:
break
def user_changes(i=None, save=False):
"""User changes a preexisting line"""
attempt = True
while i is None and attempt:
# get the line the user wants to change
i_text = raw_input("Line to be changed: ")
try:
# make user input an index
i = int(i_text)
except:
# check if they want to try again
c = user_choice("Bad input - '%s' is not an "
"integer. Try again? " % i_text, (Yes, No))
attempt = (c == Yes)
if attempt:
# user gave a valid integer for indexing
try:
user_reads(i-1)
overwrite_user_text(i-1, user_input(), save)
except Exception as e:
print("ERROR: %s" % e)
if user_choice("Try again? ", (Yes, No)):
user_changes(i, save)
# stores whatever text is already on
# file to `user_text` before use
read_from_cache()
I'm trying to make a new file at the end of a program to append info into, however the file isn't being created for some reason (the place in my code to look at is the #curve area). My best guess is that the variable "filename" established at the beginning of the program, isn't carrying all the way down to where I establish the new file name. My code is as follows:
import statistics
# input
filename = input("Enter a class to grade: ")
try:
# open file name
open(filename+".txt", "r")
print("Succesfully opened", filename,".txt", sep='')
print("**** ANALYZING ****")
with open(filename+".txt", 'r') as f:
counter1 = 0
counter2 = 0
right = 0
answerkey = "B,A,D,D,C,B,D,A,C,C,D,B,A,B,A,C,B,D,A,C,A,A,B,D,D"
a = []
# validating files
for line in f:
if len(line.split(',')) !=26:
print("Invalid line of data: does not contain exactly 26 values:")
print(line)
counter2 += 1
counter1 -= 1
if line.split(",")[0][1:9].isdigit() != True:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
if len(line.split(",")[0]) != 9:
print("Invalid line of data: wrong N#:")
print(line)
counter2 += 1
counter1 -= 1
counter1 += 1
#grading students
score = len(([x for x in zip(answerkey.split(","), line.split(",")[1:]) if x[0] != x[1]]))
score1 = 26 - score
score2 = score1 / 26
score3 = score2 * 100
a.append(score3)
sscore3 = str(score3)
# results file
results = open(filename+"_grades.txt", "a")
results.write(line.split(",")[0])
results.write(",")
results.write(sscore3[:2])
results.write("\n")
results.close()
# in case of no errors
if counter2 == 0:
print("No errors found!")
# calculating
number = len(a)
sum1 = sum(a)
max1 = max(a)
min1 = min(a)
range1 = max1 - min1
av = sum1/number
# turn to int
av1 = int(av)
max2 = int(max1)
min2 = int(min1)
range2 = int(range1)
# median
sort1 = sorted(a)
number2 = number / 2
number2i = int(number2)
median = a[number2i]
median1 = int(median)
# mode
from statistics import mode
mode = mode(sort1)
imode = int(mode)
# printing
print ("**** REPORT ****")
print ("Total valid lines of data:", counter1)
print ("Total invalid lines of data:", counter2)
print ("Mean (average) score:", av1)
print ("Highest score:", max2)
print("Lowest score:", min2)
print("Range of scores:", range2)
print("Median Score:", median1)
print("Mode score(s):", imode)
# curve
part = input("Would you like to apply a curve to the scores? (y)es or (n)o?")
if part == "y":
newmean = input("Enter desired mean score:")
part1 = newmean - av1
part2 = sscore3 + part1
results = open(filename+"_grades_with_curve.txt", "a")
results.write(line.split(",")[0])
results.write(",")
results.write(sscore3[:2])
results.write(",")
results.write(part2)
results.write("\n")
results.close()
except:
print("File cannot be found.")
and It skips to the except block when I enter "y" at the end to try and create the new list, meaning the issue is within creating this new list.
The code is too long and requires reorganization.
It is likely, there are other problems with your code and you are trying to fix wrong one.
Few hints:
Do not open file without assigning the file object to a variable
open(filename+".txt", "r")
You open the file and have no chance to close it as you ignore the returned
file object.
Use with block to open/close your files
with open(input_fname, 'r'):
# work with the file
Learn doing so everywhere.
Do not reopen file for writing results
Your code repeatedly opens the result file (in "a" mode). You have better opening it only once.
You may even open multiple files within one context block:
with open(input_fname, 'r') as f, open(output_fname, "a") as results:
# work with the files
Reuse once calculated result
In many places you split the line: line.split(",").
You shall put the result into variable and reuse it.
rec = line.split(",")
Never ignore exceptions!!! (most serious problem)
The final block is catching all exceptions without giving you any sign, what went wrong (or even
worse, it tells you probably wrong information that the file was not found).
So instead of:
try:
# some code
except:
print("File not found.")
at least reraise the exception to learn from it:
try:
# some code
except:
print("File not found.") # this is probably to be removed as misleading message
raise
In fact, you can completely ignore complete top level try - except block and let the exception show
up telling you what went wrong.
Split your code into smaller chunks.
Having the code split to smaller functions shall simplify debugging and usage
I currently have the following code: You enter a string, the computer then pulls random letters and tries to match it to the letters in your string. This repeates and with each iteration the computer gets closer to guessing your string. I would like to output the initial string entered or the 'target' and the string format of the number of iterations it took to get the correct match. I want to output this to a text document. So far the script produces a text document but does not output to it. I would like it to save the data after each iteration from the main loop. I have the working program i just need assitance with the output, any ideas on how that could be done?
Here is the progress i made:
import string
import random
possibleCharacters = string.ascii_lowercase + string.digits + string.ascii_uppercase + ' .,!?;:£$^%&*|'
file = open('out.txt', 'w')
again = 'Y'
while again == 'Y' or again == 'y':
target = input("Enter your target text: ")
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''
completed = False
generation = 0
while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
generation += 1
attemptThis = attemptNext
genstr = str(generation)
print("Target matched! That took " + genstr + " generation(s)")
file.write(target)
file.write(genstr)
again = input("please enter Y to try again: ")
file.close()
Addressing both the original question and the one in the comments:
How to write to file after each iteration of the loop: call file.flush() after file.write(...) :
file.write(target)
file.write(genstr)
file.flush() # flushes the output buffer to the file
To add a newline after each "target" and "genstring" that you write, well, add a newline to the string (or whatever other output formatting you want) :)
file.write(target + '\n')
file.write(genstr + '\n')