Python Reading and using data from file - python

I am currently trying to save scores from a quiz to an excel sheet which allows the user to read the files, but how can I use their save data to only save the last 3 scores of a user. I understand this would mean reading from the file to see the scores and then making it read how many tries the user has had etc. but I can't quite figure out how to make it so the program will only save the last 3 scores from that user or their 3 highest scores. Thank you.
if pclass == 1:
inFile = open("ascores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
inFile.close()
inFile = open("ascores.csv", 'r')
print(inFile.read())
elif pclass == 2:
inFile = open("bscores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
inFile.close()
inFile = open("bscores.csv", 'r')
print(inFile.read())
elif pclass == 3:
inFile = open("cscores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
inFile.close()
inFile = open("cscores.csv", 'r')
print(inFile.read(sorted(reader, key=lambda row: int(row[0]))))
else:
print("Sorry we can not save your data as the class you entered is 1, 2 or 3.")

You are closing the file before reading its contents.
if pclass == 1:
inFile = open("ascores.csv", 'a')
inFile.write("\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)))
content = inFile.read()
inFile.close()
inFile = open("ascores.csv", 'r')
print(content)
or more concise:
if pclass == 1:
new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1))
with open("ascores.csv", 'a') as in_file:
in_file.write(new_score)
content = in_file.read()
print(content)
Using the with statement will close the file for you.
You can edit the long new_score = "\n" + pname + ", " + str(correct) + ", " + str(round(etime, 1)) to:
new_score = "\n {}, {}, {:.1f}".format(pname, correct, etime)
see: https://docs.python.org/3.4/library/string.html#format-specification-mini-language for an explanation about string formatting.
You could also simplify your code (never repeat yourself):
def saveScore(pname, correct, etime, pclass):
score_files = {1:"ascores.csv", 2:"bscores.csv", 3:"cscores.csv"}
try:
filename = score_files[pclass]
new_score = "\n {}, {}, {:.1f}".format(pname, correct, etime)
with open(filename, 'a') as in_file:
in_file.write(new_score)
content = in_file.read()
return content
except KeyError:
return None
print(saveScore(pname, correct, etime, pclass))

Related

How can I convert an array to JSON?

I have an array that I need to convert to a JSON file. There is a text file that holds the data. But I don't understand why it only adds one record.
import collections
list = []
with open("file.txt") as f:
for line in f:
info = line.split()
lists = ("ip" + " " + info[0].replace(":", " ").split()[0] + " " + "port" + " " + info[0].replace(":", " ").split()[1] + " " + "region" + " " + info[1].replace("-", " ").split()[0]).split()
list.append(lists)
d = collections.defaultdict(dict)
for l in list:
d[l[0]] = l[1]
d[l[2]] = l[3]
d[l[4]] = l[5]
print(json.dumps(d))
with open("proxy.json", "w") as f:
f.write(json.dumps(d))
Example of a text file:
154.0.5.178:8080 ZA-N-S! -
119.28.156.115:3128 KR-N -
207.144.111.230:8080 US-H -
3.20.236.208:49205 US-H-S -
217.60.194.43:8080 IR-N! -
190.61.41.106:999 CO-N-S +
What I get:
enter image description here
info[1].replace("-", " ").split()[0]
will always return a single value! Try this:
import json
alist = []
with open("file.txt") as f:
for line in f:
info = line.split()
data = {"ip": info[0].split(":")[0], "port": info[0].split(":")[1],"region": info[1].split("-")}
alist.append(data)
print(json.dumps(alist))
with open("proxy.json", "w") as f:
f.write(json.dumps(alist))

How to select specific data from CSV files and display all the data in that row

I'm trying to make a code that shows all the details of specific students. The code takes an input of gender and their class and then shows all their data. For example, if I input "Male" and "10A", I want the code to give me all the data from the students who are male and in class 10A. All their information is stored in a CSV file (called details). My code so far is:
file = open("details.csv","rt")
gender_input = input("Input gender of students")
class_input = input("Input class of students")
for line in file:
details_of_gender = line.split(",")
details_of_class = line.split(",")
gender = str(details_of_gender[7])
class1 = str(details_of_class[8])
if gender == "Male":
if class1 == "10A":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if class1 == "10B":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if gender == "Female":
if class1 == "10A":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
if class1 == "10B":
print(details[0] + " " + details[1] + " " + details[2] + " " + details[3] + " " + details[4] + " " + details[5])
Assuming that your program isn't working just because you're using a variable details that you haven't defined before, here's a better way of doing this:
import csv
with open("details.csv", newline="") as infile:
reader = csv.reader(infile) # use the csv module to read a CSV file!
for row in reader:
gender = row[7]
class = row[8]
if gender in ("Male", "Female") and class in ("10A", "10B"):
print(" ".join(row[:6])) # join elements 0-5 with spaces

python wont write even when I use f.close

I'm trying to write some code that outputs some text to a list. output is a variable that is a string which is the name of the file to be written. However whenever I look at the file nothing is written.
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
Program looks ok, check if the output is set ok, I set as a dummy filename, it worked, presuming code within the block after open has no compiler/interpreter error. The output file should be in the same directory where the source is.
output = "aa.txt"
with open(output, 'w') as f:
f.write("Negative numbers mean the empty space was moved to the left and positive numbers means it was moved to the right" + '\n')
if A == True:
the_h = node.h
elif A== False:
the_h = 0
f.write("Start " + str(node.cargo) + " " + str(node.f) +" " +str(the_h)+" " + '\n')
if flag == 0:
flag = len(final_solution)
for i in range (1,flag):
node = final_solution[i]
f.write(str(node.e_point - node.parent.e_point) + str(node.cargo) + " " + str(node.f) +'\n')
f.close()
You should not add f.close(), as the with statement will do it for you. Also ensure you don't reopen the file elsewhere with open(output, 'w') as that will erase the file.

overwrite words in text file with python

I created a text file that contains in the first line a counter of created users and the rest of the lines the text contains user name, password..
for example:
2
username Name Last_name Password
username1 Name Last_name1 Password1
I'm using the following commands:
def SaveDatA(self):
#if self.CheckValid() == False:
#return
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
I want to update the counter to the first line
Do you want this?
f1_lines = open('data.txt', 'r').readlines()
with open('data.txt','w') as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
f1_lines[0]=str(self.counter)+'\n'
f.write(''.join(f1_lines))
With readlines() you create a list contain all of lines in the file so you change the first index of that list with f1_lines[0]=str(self.counter)+'\n' then rewrite it in to the file !
After a lot of trials this code work's:
with open("data.txt","a") as f:
f.write(self.userEntry.get() + " " + self.NameEntry.get() + " " + self.LastEntry.get()+ " " + self.PasswordEntry.get() + "\n")
self.counter += 1
fileCopy = open('data.txt', 'r').readlines()
fileCopy[0] = fileCopy[0][1:]
with open("data.txt","w") as f:
f.write(str(self.counter)+" ")
f.write("".join(fileCopy))
but maybe there is another better way ?

Python Nested Loop Fails

I am writing a program to perform file integrity checks of files in a directory. There are 3 nested loops in the code. When I run the code, the first two loops work great but the third loop does not run more than once.
import hashlib
import logging as log
import optparse
import os
import re
import sys
import glob
import shutil
def md5(fileName):
"""Compute md5 hash of the specified file"""
try:
fileHandle = open(fileName, "rb")
except IOError:
return
m5Hash = hashlib.md5()
while True:
data = fileHandle.read(8192)
if not data:
break
m5Hash.update(data)
fileHandle.close()
return m5Hash.hexdigest()
req = open("requested.txt")
for reqline in req:
reqName = reqline[reqline.rfind('/') + 1:len(reqline) - 1]
reqDir = reqline[0:reqline.rfind('/') + 1]
ezfimlog = open("ezfimlog.txt", 'a')
actFile = open("activefile.txt")
tempFile = open("activetemp.txt", 'w')
for name in glob.glob(reqDir + reqName):
fileHash = md5(name)
actInt = 0
if fileHash != None:
print fileHash
for actLine in actFile:
actNameDir = actLine[0:actLine.rfind(' : ')]
actHash = actLine[actLine.rfind(' : ') + 3:len(actLine) -1]
print (name + " " + actHash + " " + fileHash)
if actNameDir == name and actHash == fileHash:
tempFile.write(name + " : " + fileHash + "\n")
actInt = 1
if actNameDir == name and actHash != fileHash:
tempFile.write(name + " : " + actHash + "\n")
actInt = 1
ezfimlog.write("EzFIM Log: The file " + name + " was modified: " + actHash + "\n")
if actInt == 0:
ezfimlog.write("EzFIM Log: The file " + name + " was created: " + fileHash + "\n")
tempFile.write(name + " : " + fileHash + "\n")
shutil.copyfile("activetemp.txt", "activefile.txt")
You open actFile once and then try to read it many times. You'll need to open it each time you want to read it.
Move this line:
actFile = open("activefile.txt")
to just before this line:
for actLine in actFile:

Categories