Opening a file for append error - python

I'm trying to open a file for appending, but I keep getting the "except" portion of my try/except block, meaning there is some sort of error with the code but I can't seem to find what exactly is wrong with it. It only happens when I try to open a new file like so:
results = open("results.txt", "a")
results.append(score3)
Here's my full code:
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)
# results file
results = open("results.txt", "a")
results.write(score3)
# 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)
results.close()
except:
print("File cannot be found.")

I don't think there is a method called append for writing into file. You can use the write or writelines method only to write. As you already opened the file with append permissions. It wont change the old data and will append the text to the file.
f=open('ccc.txt','a')
f.write('Hellloooo')
f.close()
Hope it helps.

Related

I'm getting a ValueError: cannot convert string to float: ".". What is going on?

I am trying to write a function that takes in a file with numerical values, total them all up while excluding all numbers with a letter, and find the average. However, when I try to convert a number like "3.9" to float form, I get the ValueError: cannot convert string to float: ".". I know that if I just did a straight conversion of "3.9" to float form via float("3.9") type casting it would work.
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for line in content:
for element in line:
if float(element) > 2:
total += float(element)
print(lineSplit)
average = total / count
print(average)
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()
File contents:
35.2
1.8
65.6
67.9z
70.2
73.2 a3.9 65.6 69.8
6$4.9
54.9
Oops, just fixed my own question with the code below:
def averageSpeed():
count = 0
total = 0
stripLst = 'abcdefghijklmnopqrstuvwxyz$'
while count < 2:
try:
filename = input("Enter a file to process: ")
instance = open(filename, "r")
content = instance.readlines()
for line in content:
print(line)
print()
for line in content:
lineSplit = line.split()
for element in lineSplit:
for letter in element:
for character in stripLst:
if letter == character:
lineSplit.remove(element)
for element in lineSplit:
if float(element) > 2:
total += float(element)
count += 1
print(lineSplit)
average = total / count
print("The total of the speeds of {} excluding all speeds with lettres in them is {}.".format(filename, total))
print("The total number of speeds in {} without letters is {}.".format(filename, count))
print("The average of the speeds of {} excluding all speeds with letters in them is {}.".format(filename, average))
break
except (FileNotFoundError):
print("That file does not exist.")
count += 1
filename = input("Enter a file name that exists: ")
averageSpeed()

fastest way to check a .rar file password - other than rarfile extractall

So i have written a little .rar password "cracker" based on tutorials, using the code underneath. It works fine, but is very slow when the file size is big. The best reason i could find is, that ever so often when you put in a wrong password, it extracts the whole file, before refusing the password. With small files that is not a big problem, but with big files it slows the process a lot.
Is there a way to just check a hashed version of the password against a iterated hash?
import itertools
import rarfile
import time
rarfile.UNRAR_TOOL = "path"
rar = rarfile.RarFile("path")
done = False
n = 0
inputList = ["A","B","1","2"]
class h():
startword = ""
rep = 1
start = 0
itrTot = 0
f = open("save.txt")
for x,each in enumerate(f):
if x == 0:
h.rep = int(each)
else:
h.start = int(each)-3
f.close()
if h.start < 0:
h.start = 0
h.itrTot = len(inputList)**h.rep
def pw_guess():
res = itertools.product(inputList, repeat=h.rep)
for guess in res:
yield guess
start_time = time.time()
while True:
guess_generator = pw_guess()
for guess in guess_generator:
n += 1
if h.startword == "":
h.startword = guess
else:
if guess == h.startword:
h.rep += 1
n = 0
h.itrTot = len(inputList)**h.rep
h.start = 0
print("next rotation, itr rep: "+str(h.rep))
h.startword = ""
break
if n < h.start:
continue
txt = f"({n}/{h.itrTot}, {round((100/h.itrTot)*n,2)}%) - {h.rep}: {''.join(guess)}"
print(txt)
try:
rar.extractall(path="path",members=None,pwd=''.join(guess))
print("Pass found!")
print(str(n) + " - " + str(h.rep) + ": " + str(''.join(guess)))
done = True
txt2 = f"({n}/{h.itrTot}, {round((100/h.itrTot)*n,2)}%) - {h.rep}: {''.join(guess)}\n"
f = open("pass.txt", "a")
f.write(txt2)
f.close()
break
except:
f = open("save.txt", "w")
f.write(str(h.rep) + "\n" + str(n))
f.close()
if done:
end_time = time.time()
break
print("End time: " + str(end_time-start_time))
John the ripper is the answer. +20k passwords checked in 2 minutes. But using parts of the script for wordlist generation, is still very fast and functional.
wordlist generator i used:
import itertools
inputList = ["A","B","C","D","1","2","3","4","5"]
itr = 7
WL_path = "path"
f = open(WL_path,"w")
f.write("")
f.close()
class h():
startword = ""
rep = 1
itrTot = 0
txt = ""
h.itrTot = len(inputList)**itr
print("Wordlist length: " + str(h.itrTot))
def pw_guess():
res = itertools.product(inputList, repeat=h.rep)
for guess in res:
yield guess
while True:
guess_generator = pw_guess()
for guess in guess_generator:
if h.startword == "":
h.startword = guess
else:
if guess == h.startword:
h.rep += 1
print("next rotation, itr rep: " + str(h.rep))
h.startword = ""
break
h.txt = ''.join(guess)
f = open(WL_path, "a")
f.write(h.txt+"\n")
f.close()
if h.rep > itr:
break

How to align two columns perfectly in python?

I have an assignment where we have to read the file we created that has the test names and scores and print them in columns. Getting the data and displaying it, along with the average, is no problem, but I do not understand how to align the scores to the right in the output column. In the output example the scores line up perfectly to the right of the "SCORES" column. I can format their width using format(scores, '10d') as an example, but that's always relative to how long the name of the test was. Any advice?
def main():
testAndscores = open('tests.txt', 'r')
totalTestscoresVaule = 0
numberOfexams = 0
line = testAndscores.readline()
print("Reading tests and scores")
print("============================")
print("TEST SCORES")
while line != "":
examName = line.rstrip('\n')
testScore = float(testAndscores.readline())
totalTestscoresVaule += testScore
## here is where I am having problems
## can't seem to find info how to align into
## two columns.
print(format(examName),end="")
print(format(" "),end="")
print(repr(testScore).ljust(20))
line = testAndscores.readline()
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
print("Average is", (averageOftheTestscores))
#close the file
testAndscores.close()
main()
You just have to store each name and score in a list, then calculate the longest name, and use this length to print space for shorter name.
def main():
with open('tests.txt', 'r') as f:
data = []
totalTestscoresVaule = 0
numberOfexams = 0
while True:
exam_name = f.readline().rstrip('\n')
if exam_name == "":
break
line = f.readline().rstrip('\n')
test_score = float(line)
totalTestscoresVaule += test_score
data.append({'name': exam_name, 'score': test_score})
numberOfexams += 1
averageOftheTestscores = totalTestscoresVaule / numberOfexams
longuest_test_name = max([len(d['name']) for d in data])
print("Reading tests and scores")
print("============================")
print("TEST{0} SCORES".format(' ' * (longuest_test_name - 4)))
for d in data:
print(format(d['name']), end=" ")
print(format(" " * (longuest_test_name - len(d['name']))), end="")
print(repr(d['score']).ljust(20))
print("Average is", (averageOftheTestscores))
main()

optimizing my Benfold's law program

lines=[]
count1 = 0
count2 = 0
count3 = 0
count4 = 0
count5 = 0
count6 = 0
count7 = 0
count8 = 0
count9 = 0
allcount = 0
with open('city_all.txt', 'r') as file:
for line in file:
lines.append(line.strip())
for x in range(0,len(lines)):
if lines[x].isdigit():
allcount+=1
string = lines[x]
if string[0]=="1":
count1+=1
elif string[0]=="2":
count2+=1
elif string[0]=="3":
count3+=1
elif string[0]=="4":
count4+=1
elif string[0]=="5":
count5+=1
elif string[0]=="6":
count6+=1
elif string[0]=="7":
count7+=1
elif string[0]=="8":
count8+=1
elif string[0]=="9":
count9+=1
print(count1/allcount)
print('{:.1%}'.format(count1/allcount))
Wondering if there is anyway to not have to declare all my variables, and compact all the if statements?Trying to make a program to help compute Benfold's law, so I am putting a txt file into a list, then going through each element and checking what the starting digit is.
You can simplify it a bit:
counts = [0 for _ in range (10) ]
with open('city_all.txt', 'r') as f:
for line in (x.strip () for x in f):
if line.isdigit():
allcount += 1
try: counts[int(line)] += 1
except IndexError: pass

wrap all lines that are longer than line length

I am writing a program that limits each line to a certain length.
this is what i got so far, i am almost done but i still need to cut each line, but i cant figure it out.
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r+')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
wr = textwrap.TextWrapper()
wraped = wr.wrap(file)
print("Here is your output formated to a max of", lLength, "characters per line: ")
wr.width = lLength
wr.expand_tabs = True
for lines in wraped:
print(lines)
Edit:
def main():
filename = input("Please enter the name of the file to be used: ")
openFile = open(filename, 'r')
file = openFile.read()
lLength = int(input("enter a number between 10 & 20: "))
while (lLength < 10) or (lLength > 20) :
print("Invalid input, please try again...")
lLength = int(input("enter a number between 10 & 20: "))
if (lLength > 10) or (lLength < 20):
print("\nYour file contains the following text: \n" + file)
#=========================================================================
wr = textwrap.TextWrapper(width=lLength)
wraped = wr.wrap(file)
print("\n\nHere is your output formated to a max of", lLength, "characters per line: ")
for lines in wraped:
print(lines)
main()
an example of what the output SHOULD be is this.
If the file specified contains this text:
hgytuinghdt #here the length is 11
ughtnjuiknshfyth #here the length is 16
nmjhkaiolgytuhngjuin #here the length is 20
and the lLength is specified to 15 then this should print out:
hgytuinghdt
ughtnjuiknshfyt
h
nmjhkaiolgytuhng
juin
wr = textwrap.TextWrapper() should be wr = textwrap.TextWrapper(width=length, expand_tabs=True)
You should then remove wr.width = lLength and wr.expand_tabs = True. They should have been run before wr.wrap() was called, but since one can set it using keyword arguments in the TextWrapper constructor as shown at the very top, they can be removed.
PS: for lines in wraped: print(lines) can be replaced with print(wraped) if you use TextWrapper.fill.
Try this:
line = 'nmjhkaiolgytuhngjuin'
n = 5 # set the width here
a = [line[i:i+n] for i in range(0, len(line), n)]
print ("\n".join(a))
This might help you:
def wrap(f,n):
fi=open(f,"w+")
rl=fi.readlines()
for i in range(0,len(rl)):
if len(rl[i]) > n:
fi.write(rl[i][:n] +"\n" + rl[i][n:])
fi.Close()
else:
fi.write(rl[i])
fi.close()

Categories

Resources