Python: Problem closing files in a while loop - python

I've ran into an error while dealing with a while loop. I am able to input the number I want to run, and the results are written correctly to the corresponding .CSV. Once the section for that number is done running, it will ask if I want to try again with a new number. It runs the new numbers code and creates the new .CSV but the filesize stays at 0kb. I thought this has to do with closing the file once complete but I have written the f#.close() in there.
Ex: Choose number 1, code for #1 runs and saves .CSV correctly, choose Yes for another run and new number (#2), code #2 runs but does not correctly close thus not saving any info to the second CSV.
This happens regardless of which number I choose first or second. (ex: choose 3 first, 3 runs fine and saves fine. Then choosing 2 and runs but does not save correctly.)
Here is my current code:
f1 = file('1.csv', 'rb')
f2 = file('2.csv', 'rb')
f3 = file('3.csv', 'rb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.reader(f3)
number = raw_input("Enter number: ")
while True:
if number == "1":
f4 = file('No_1_Results.csv', 'wb')
c4 = csv.writer(f4)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f4.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #1"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number == "2":
f5 = file('No_2_Results.csv', 'wb')
c5 = csv.writer(f5)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f5.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #2"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number =="3":
f6 = file('No_3_Results.csv', 'wb')
c6 = csv.writer(f6)
<snip> #do stuff here
print "Took ", time.time() - start, "seconds."
f6.close()
reset_answer = raw_input("Again? Type Y or N : ")
if reset_answer == ("n" or "N"):
print "Bye! from #3"
break
if reset_answer == ("y" or "Y"):
number = raw_input("Enter new number #: ")
continue
if reset_answer != ("n" or "N" or "y" or "Y"):
print "Y or N only allowed. Try again."
continue
if number is not "1" or "2" or "3":
print "Invalid number selected."
number = raw_input("Please choose a number: ")
continue
f1.close()
f2.close()
f3.close()
Note: Using Python 2.6 on Windows / still learning python -

It would be nice to know what you are exactly doing with the file descriptor you opened at the beginning of the loop (f1, f2, f3). Nevertheless I believe that the issue you have is related with the fact that you are trying to read twice from one of those file descriptors but you are not resetting their position when doing it. Take look at the following:
$ echo "Test reading from a file" >> test.out
$ python
>>> f1 = file('test.out')
>>> f1.readlines()
['Test reading from a file\n']
>>> f1.readlines()
[]
After reading from a file the file descriptor remembers your position form the last read. To solve your issue you would have to perform a seek and going to the beginnings of the file:
$ echo "Test reading from a file" >> test.out
$ python
>>> f1 = file('test.out')
>>> f1.readlines()
['Test reading from a file\n']
>>> f1.seek(0)
>>> f1.readlines()
['Test reading from a file\n']
I hope this is the issue you have, otherwise you should show the logic that you have when reading the file.

import csv
try:
inp = raw_input # Python 2.x
except NameError:
inp = input # Python 3.x
def processFile(infname, outfname, perRow):
with open(infname,'rb') as inf, open(outfname,'w') as outf:
incsv = csv.reader(inf)
outcsv = csv.writer(outf)
outcsv.writerows(perRow(row) for row in incsv)
print("{0} -> {1} successful".format(infname, outfname))
def doStuff(row):
# do stuff here
return row
def main():
while True:
name = inp('Enter next file name (or nothing to exit)')
if name.strip():
try:
processFile(name+'.csv', name+'_result.csv', doStuff)
except IOError, e:
print(e)
else:
print("Goodbye.")
break
if __name__=="__main__":
main()
Edit: after looking at your link to Python: Comparing two CSV files and searching for similar items I would continue with
def readMasterList():
res = {}
with open('masterlist.csv','rb') as inf:
incsv = csv.reader(inf)
head = incsv.next() # skip header row
for rownum,dat in enumerate(incsv):
res[tuple(dat)] = rownum
return res
masterList = readMasterList()
def doStuff(row, _ml=masterList):
key = (row[1], row[3])
try:
rownum = _ml[key]
row.append("FOUND in master list (row {0})".format(rownum))
except KeyError:
row.append("NOT FOUND in master list")
return row

Related

Why is my code not posting the requested columns in main def?

I don't expect any coding answers, more just guidance. For my project I have to date-mine apple stock prices from a csv-file and implement it in my code. I provided a sample output below.
https://imgur.com/rPOPN1I
Right now, I am not getting any error messages but my code is not posting the columns requested from the csv.file. Are my definitions at fault or am I missing something else?
# Project No.: 5
# Author: burntchickennuget
# Description: making definitions, reading from a .csv file, validating input, data-mining,
f_list = list()
file_object = ()
my_tot = dict()
new_list = list()
def get_input_descriptor():
while True:
filename = input("Enter a file name: ")
if filename == 'table.csv':
with open(filename, "r") as infile:
infile.readlines()[1:]
# for line in lines:
# print(line.rstrip())
break
else:
print("Bad file name, try again")
return filename
def get_data_list(file_object, column_number):
dict = {}
for val in file_object:
date = val.split(",")[0]
data = float(val.split(",")[column_number])
dict[date] = data
return dict.items()
def average_data(new_list):
for date, price in new_list:
my_tot[date] = my_tot.get(date, 0) + float(price)
my_times[date] = my_times.get(date, 0) + 1
for key in my_tot:
f_list.append((float(my_tot[key] / my_times[key]), key))
def main():
get_input_descriptor()
column_number = int(input("Which column: "))
date_list = get_data_list(file_object, column_number)
final_list = average_data(date_list)
x = sorted(f_list)
print('Lowest 6:')
for tup in x[:6]:
print
tup[0], tup[1]
print('Highest 6:')
x = sorted(f_list, reverse=True)
for tup in x[:6]:
print
tup[0], tup[1]
while 1:
flag = input("do you want to continue? ")
if flag == '' or not flag[0].lower() in ['y', 'n']:
print("Please answer with a yes or no")
else:
break
if flag[0].lower() == 'y':
column = input("Which column: ")
print(column)
if flag[0].lower() == 'n':
print("Bye!")
if __name__ == "__main__":
main()
What can I try next?
Take a look around your get_input_descriptor method.
What are you returning from the method?
Where is the returned information being stored in the main method (is it being stored at all?)
What are you doing with the lines that you read from the file?
What is the file_object you are passing into get_data_list
My main advice would be to add print everywhere for debugging. See what it stored in your variables at different points in the program and see where a variable doesn't contain what you think it should

Python password system with lock after certain number of attempts

So I am trying to create a password system in Python, whereby after a certain number of incorrect attempts, the user will be blocked from accessing it for, say, 5 minutes. I am currently unsure how the values of the variables can be kept after rerunning the same file and then used in this manner. Could someone help me with this, as I am currently still new to Python?
Update:
After experimenting for a while with the code Jonas Wolff provided me I finalised my code to the following:
def password():
count = 0
currentTime = float(time.time())
passwordList = ["something", "password", "qwerty", "m42?Cd", "no"]
passwordNum = random.randint(0, 4)
password = passwordList[passwordNum]
with open("password.txt", "r") as file:
check = file.readline()
initialTime = file.readline()
if initialTime=="":
initialTime==0
if int(check)==1 and (currentTime-float(initialTime))<300:
print("You are still locked")
print("Please try again in", int(300-(currentTime-float(initialTime))), "seconds.")
quit()
print("The randomised password is No.", passwordNum+1) #Prints a string to let the user know which password was randomly selected
while count<5:
inp = input("Enter the Password: ")
if inp==password:
print("Access Granted")
print()
f = open("password.txt", "w")
f.write("0\n0")
f.close()
select()
elif (count+1)==5:
print("You have been locked")
print("Please try again in 5 minutes")
f = open("password.txt", "w")
f.write("1\n")
f.write(str(currentTime))
f.close()
quit()
else:
count+=1
print("Incorrect Password")
print("You have", 5-count, "tries left.")
continue
Thanks a lot for the help you have provided and the patience with which you answered my questions.
import YourProgram # this is the program you want to run, if the program runs automaticly when opened then move the import to the part where i wrote YourProgram() and delete the YourPregram() line
import time
pswd = "something"
count = 0
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
numa = file_info.count("1")
count = numa
while True:
with open("PhysxInit.txt","r") as file:
file_info = file.readline()
tima = file.readline()
inp = input("What is the password:")
if inp == pswd:
if tima == "":
tima = "0" # this should solve yoúr problem with float convertion however it doesn't make sence that this step should be needed
if str(file_info[:5]) != "11111" or time.time() > float(tima):
YourProgram() # this is just meant as the thing you want to do when when granted acces i magined you where blocking acces to a program.
f = open("PhysxInit.txt", "w")
f.write("\n")
f.close()
break
else:
count += 1
f = open("PhysxInit.txt", "w")
f.write(("1"*count)+"\n"+str(tima))
if count == 5:
f.write(str(time.time()+60*5))
f.close()
#f = open("PhysxInit.txt", "w")
#f.write("\n")
#f.close()
does this work?
just make sure you have a text file called PhysxInit.txt
after running the program, and having guessed wrong a few times my txt file look like this.
11111
1536328469.9134998
it should look something like mine though the numbers may be diffrent.
To read a specific line as you requested you need to do:
with open("PhysxInit.txt", "r") as f:
for w,i in enumerate(f):
if w == #the number line you want:
# i is now the the line you want, this saves memory space if you open a big file

reading, writing, appending, and deleting files in python

here's my code, i could use your help.
My program is supposed to accept data input, create new text files,read and write into text files, append text into already existing text files, truncate and delete files.
Now the problem i have with my program is that the the part of the code that is supposed to append text, truncate the content of a text file and delete a text file is not working and the program does not return any errors during run time.
import os
from sys import argv
filename = argv
def menu():
holder = input("enter 1 to create new file or 2 to use existing ones\n")
if holder == 1:
dam = raw_input("Enter name of new text file:\n")+'.txt'
textfile = open(dam, 'w+')
happ = raw_input("\nPlease enter record into your new file\n\n")
textfile.write(happ)
textfile.close()
print "*******************"
print "*******************\n"
print "To view the content of your new file, enter 'yes' otherwise enter 'no' to exit"
gett = raw_input()
if gett == 'yes':
print "*******************"
print "\nyour inputted record is>>>\n"
display = open(dam)
print(display.read())
print'\n'
menu()
elif gett == 'no':
print ("\nOk, see you later. Have a nice day!")
print'\n'
menu()
else:
print "\nyou have entered a wrong input"
print '\n'
menu()
elif holder == 2:
filename = raw_input("Enter name of file:\n")+'.txt'
entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
if entry == 7:
print ("Displayed below is the content of your file, continue to append more text at the bottom of the file.(text is limited to 3 lines)\n")
textfiles = open(filename, 'a+')
print (textfiles.read())
line1 = raw_input( )
line2 = raw_input( )
line3 = raw_input( )
print "\nSaving..."
textfiles.write(line1)
textfiles.write('\n')
textfiles.write(line2)
textfiles.write('\n')
textfiles.write(line3)
textfiles.write('\n')
print "\nSaved!"
textfiles.close()
elif entry == 8:
textfiles = open(filename, 'w')
print "Truncating the file..."
textfiles.truncate()
print "Done, truncated."
textfiles.close()
right = raw_input("Do you want to write into this file? Y/N : ")
if right == 'Y':
textfiles = open(filename, 'a+')
print "text is limited to 3 lines"
line1 = raw_input('\n')
line2 = raw_input()
line3 = raw_input()
print "\nSaving..."
textfiles.write(line1)
textfiles.write('\n')
textfiles.write(line2)
textfiles.write('\n')
textfiles.write(line3)
textfiles.write('\n')
print "\nSaved!"
textfiles.close()
else:
print "Ok have a nice day"
elif entry == 9:
print "Deleting the file..."
try:
os.remove(filename)
except OSError, e: #if failed, report it back to the user
print ("Error: %s - %s." % (e.filename, e.strerror))
print "Done, deleted."
else:
print "Error! wrong entry"
print '\n'
menu()
else:
print "\nyou have entered a wrong input"
print '\n'
menu()
menu()
This is the output it gives
enter 1 to create new file or 2 to use existing ones
2
Enter name of file:
test
Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : 8
Error! wrong entry
enter 1 to create new file or 2 to use existing ones
ANY HELP ON HOW TO MAKE THIS WORK?
You are using the function raw_input() for your variable entry at the line
entry = raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
Refering to the documentation of python2 (https://docs.python.org/2/library/functions.html#raw_input), the function raw_input return a String.
After, you are testing your variable entry against integer values. Since a String never equals an int, the test won't work. And your code fall in the last condition block which is "wrong input"
To fix this issue, you should use the input function like you did at the begining of your code (https://docs.python.org/2/library/functions.html#input):
entry = input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : ")
or cast entry to int
entry = int(raw_input("Press 7 to append text into this file, 8 to truncate the content of this file, or 9 to delete this file : "))

Use values saved to a file in order to compute mean/median/mode/etc

I have a program that saves a file that you can write values to. What I am trying to do is use the saved files to calculate my mean/median/mode and to be able to delete values. functions. I am able to add values to the file through the open("filename","a")...but how do I make it so that I am able to import the file values to calculate my other functions?
Sorry its so long, but if anyone can help I would really appreciate it, I am new to figuring out File IO a stuff.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
def main(filename):
print("Now what would you like to do?")
print("--------------------------------------------------------------------------------")
print("Press 1 if you would like to ADD a Value to your list")
print("Press 2 if you would like to DELETE a Value from your list according to its value")
print("Press 3 if you would like to DELETE a Value from your list according to its location")
print("Press 4 if you would like to DISPLAY your List")
print("Press 5 if you would like to COMPUTE MEAN for your list")
print("Press 6 if you would like to COMPUTE MEDIAN for you list")
print("Press 7 if you would like to COMPUTE MIDPOINT for you list")
print("Press 8 if you would like to COMPUTE MODE(S) for your list")
print("Press 9 if you would like to COMPUTE STANDARD DEVIATION for your list")
print("Press 10 if you would like to READ values from a FILE you have made")
print("Press 0 if you would like to EXIT")
print()
execute = int(input("which action would you like to do next?"))
if execute == 1:
add_Values(filename)
if execute == 2:
remove_Value_List(filename)
if execute == 3:
del_Value_Location(filename)
if execute == 4:
read_file(filename)
if execute == 5:
computing_Mean(filename)
if execute == 6:
computing_Median(filename)
if execute == 7:
computing_Midpoint(filename)
if execute == 8:
computing_Modes(filename)
if execute == 9:
computing_Standard_Dev(filename)
if execute == 10:
read_file(filename)
if execute == 0:
print()
print("That's too bad I was having so much fun...but okay...bye!")
if execute >= 12:
print("Sorry but that is not one of the options")
if execute <= -1:
print("Sorry but that is not one of the options")
def add_Values(filename):
fout = open(filename,"a")
again = 'y'
while again == 'y':
fout.write(input("Enter a number you want to write to the file:")+"\n")
print("Do you want to add another number?")
again = input("y = yes, anything else = no:")
fout.close()
print("The numbers have been saved to the file")
main(filename)
def remove_Value_List(filename):
fout = open(filename, "r")
fout.readlines()
remove = "y"
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = float(input("Which value should I remove?"))
try:
values.remove(number_list)
print("Here is the revised list:")
print()
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def del_Value_Location(filename):
remove = "y"
fout = open(filename,"r")
fout.readlines()
while remove == "y":
print()
print("Here is your list:")
add_Values(filename)
number_list = int(input("Which position should I remove?"))
try:
del values[number_list]
print("Here is the revised list:")
read_file_one(filename)
print()
except ValueError:
print("That item is not found in the list.")
number_list = float(input("which value should I remove?"))
remove = input("Would you like to remove a value? y = yes, amything else = no:")
fout.close()
print()
main(filename)
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += float(line.strip())
print ("Mean value is:" (summ/cnt))
def computing_Median(filename):
fin = open(filename,"r")
fin.readlines()
ordered = sorted(filename)
length = len(filename)
print("The median of this list is:")
print(float((ordered[length//2] + ordered[-(length+1)//2]))/2)
main(filename)
def computing_Midpoint(filename):
with open(filename,"r") as fout:
filename.sort(key=int)
minNum = min(float(filename))
maxNum = max(float(filename))
print("The midpoint of this list is:")
print((minNum + maxNum) / 2)
main(filename)
def computing_Modes(filename):
from collections import Counter
data = Counter(filename)
print("The Mode(s) of this list is/are:")
print(data.most_common(1))
main(filename)
def computing_Standard_Dev(filename):
mean = sum(filename)/len(filename)
for i in values:
total = 0
newDev = i - mean
squared = newDev**2
total = (total + squared)
divider = (total/(len(values)-1))
standardDev = divider**.5
print("The standard deviation is:")
print(standardDev)
main(filename)
def read_file(filename):
fin = open(filename, 'r')
L = fin.readlines()
for ix in range(len(L)):
L[ix]=L[ix].strip()
while "" in L:
L.remove("")
for ix in range(len(L)):
L[ix]=float(L[ix])
fin.close()
print(L)
main(filename)
main(filename)
There are lots of errors in your code which are very similar to each other so I will explain only one of those similar ones and you should fix others by examining fixed one.
For startes you are opening a file named filename. Using quotes around it makes it a string. You should use it like this:
def add_Values(filename):
fout = open(filename,"w")
But using with statement to open files is much more better because file is closed automatically even if exception is raised.
def add_Values(filename):
with open(filename) as fout:
#do smth
There is no file to work with in def del_Value_Location(filename): and some others. You should open your file in those as well.
To make calculations you need read your data from your file. Which can be achieved by using file.readlines()
def computing_Mean(filename):
with open(filename,"r") as fout:
summ = 0
cnt = 0
for line in fout.readlines():
cnt += 1
summ += int(line.strip())
print ("Mean value is: %.1f" % (summ/cnt))
If you want to change how many digits you want to see, you should change %.1f part.
With this you should fix your other computations by yourself.
About menu, you can do something like this to make it appear again without using a second function.
filename = input("What do you want to name your file? Be sure to include .txt after the filename!:")
#exclude this filename in main and use it as `main`s argument.
def main(filename):
print("Now what would you like to do?")
Ofcoure after this, you should change all main_two()s to main(filename).

Python (latest version) Syntax Error

I wrote this sample program that is meant to open a text file (database1.txt) from the computer, and display the results that are currently in the file. Then prompt the use if their name is in the document, if it is it should print the contents of the text file then close, otherwise it should prompt the user to enter their first name, then the program writes the name into the same text document, then prints the contents of the text file again so that the user can see the new added data. I have typed the code, and somehow it keeps saying I have a syntax error. I checked a few times and I cannot fix the error. I was wondering if someone could take a look and if they might be able to explain the error to me. Thank you
#This program reads/writes information from/to the database1.txt file
def database_1_reader ():
print('Opening database1.txt')
f = open('database1.txt', 'r+')
data = f.read()
print data
print('Is your name in this document? ')
userInput = input('For Yes type yes or y. For No type no or n ').lower()
if userInput == "no" or userInput == "n"
newData = input('Please type only your First Name. ')
f.write(newData)
f = open ('database1.txt', 'r+')
newReadData = f.read()
print newReadData
f.close()
elif userInput == "yes" or userInput == "ye" or userInput == "y"
print data
f.close()
else:
print("You b00n!, You did not make a valid selection, try again ")
f.close()
input("Presss any key to exit the program")
database_1_reader()
print is a function in py3.x:
print newReadData
should be :
print (newReadData)
Demo:
>>> print "foo"
File "<ipython-input-1-45585431d0ef>", line 1
print "foo"
^
SyntaxError: invalid syntax
>>> print ("foo")
foo
statements like this:
elif userInput == "yes" or userInput == "ye" or userInput == "y"
can be reduced to :
elif userInput in "yes"

Categories

Resources