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
Related
This code is trying to open a txt document read the names print them then ask to input a name and search for the name but the search doesn't work with text only with set names if anyone can help. I think its using data a a search request so don't know how to make the names it
def liner_search():
with open ("example.txt", "r") as myfile:
data = myfile.read().splitlines()
print (data)
numberList = [data]
searchRequest = input("enter name:")
print(searchRequest)
found = False
i=0
while found == False and i != len(numberList):
if numberList[i] == searchRequest:
print ("found")
found = True
else:
print("next")
i = i+1
liner_search()
this is the result
I propose a more pythonic approach:
def name_finder():
with open('example.txt', 'r') as my_file:
data = my_file.read().splitlines()
name = input("enter name:")
if name in data:
print("Name is in the list")
else:
print("Name is not in the list")
name_finder()
I have a text file set out in this layout:
Greg,Computer Science,Hard,5
Alex,Computer Science,Medium,2
Fiona,Maths,Easy,0
Cassie,Maths,Medium,5
Alex,Maths,Medium,1
In my program I want the user to be able to choose a certain name and see their results. My code for this looks like this:
name = input("Enter name: ")
for each in file:
each = each.split(",")
realName = each[0]
subject = each[1]
difficulty = each[2]
score = each[3]
if name == realName:
print(subject, difficulty, score)
break
else:
print()
print("Invalid name.")
name = input("Re-enter your name: ")
A few things are wrong with it though and I can't figure out what to do:
If the user entered "Alex", only one of his results will be displayed.
If a wrong name is inputted once, every other name inputted will return as "Invalid".
If the correct name is inputted and the results are displayed, the program will continue to ask for a name.
Does anybody have any solutions to these problems?
If you're going to query your file repeatedly, I'd recommend pre-loading your data once into a dictionary, and printing data as and when needed. Something like this:
data = {}
with open('file.txt', 'r') as file:
for line in file:
realName, subject, difficulty, score = each.split(',')
data.setdefault(realName, []).append((subject, difficulty, score))
while True:
name = input('>>> ')
data.get(name, 'Invalid Name')
This solves problems one and two. If you just want to break after the first valid name is input, you can query the return value of dict.get:
while True:
name = input('>>> ')
result = data.get(name)
if result:
print(result)
break
print('Invalid name')
This solves problem three.
You're better off using the csv module since your file syntax is simple CSV.
Then you can loop through the rows (each row will be an array of values).
import csv
def parse_csv_file(csv_file, operation, value, index):
with open(csv_file, newline='') as file:
reader = csv.reader(file, delimiter=',',
quotechar='|')
return operation(reader,
value, index)
def find_first_row(csv_reader, value, index):
for row in csv_reader:
if row[index] == value:
return row
return None
def main():
query = input('Enter a name: ')
result = parse_csv_file('file.csv',
find_first_row,
query, 0)
if result:
print(result)
else:
print('Nothing found!')
main()
im trying to create a database by using dictionaries. i convert the dictionary into a string once ive finished adding and deleting things from it but when i want to save the string, i would like the the keys to be on a new line from each other.
here is my code so far:
print('|-----Welcome to the Address Book-------|')
print('|----------------------------------------|')
print('|Please choice from the following:-------|')
print('|----------1: Find Contact------------|')
print('|----------2: Add Contact------------|')
print('|----------3: Delete Contact------------|')
print('|----------4: Quit Address Book----------|')
choice = [1, 2, 3, 4, 5]
document = open('addresses.txt', 'r+')
address = {}
for line in document:
if line.strip():
key, value = line.split(None, 1)
address[key] = value.split()
document.close()
open('addresses.txt', 'w')
while 1:
answer = 0
while answer not in choice:
try:
answer = int(input("Enter here: "))
except ValueError:
0
if answer == 1:
x = input('Enter his/her name: ')
if x in address:
print("This is their address: ", address[x])
else:
print('Contact does not exist!')
if answer == 2:
x = (input('Enter new contact: '))
x = x.replace(" ", "_")
if x in address:
while True:
z = str(input('Contact '+x+' with address: '+str(address[x]) + ' already existed, do you want to override?(Yes/No)'))
if z == 'yes':
b = input('Enter Address: ')
c = input('Enter postcode: ')
del address[x]
break
elif z == 'no':
break
else:
print('Please choose yes or no')
else:
b = input('Enter Address: ')
c = input('Enter postcode: ')
b = b.replace(" ", "_")
c = c.replace(" ", "_")
address[x] = b, c
if answer == 3:
z = input('Enter whom you would like to delete: ')
if z in address:
del address[z]
else:
print('Contact does not exist!')
if answer == 4:
a = "{}':(),[]"
ok = str(address)
for char in a:
ok = ok.replace(char, "")
document = open('addresses.txt', 'r+')
document.write(ok + '\n')
document.close()
break
when saving to file, i would like to save each key and its info like this:
>Bob address postcode
>Sam address postcode
but instead it is saved like this:
>Bob address postcode Sam address postcode
When writing a dictionary to file, do the following:
with open('/file/path', 'w') as f:
for k, v in d.items():
f.write(k + v + "\n")
This assumes a few things:
You want to overwrite the file, not append; if you do, switch 'w' to 'a'
All the key and value items are str
I don't like using 'r+'. You should open(filename, "r") when you want to read from a file and open(filename, "w") when you want to read your file. In my opinion, it's way easier because while using 'r+', you have to think about where the seek is (the blinking cursor that you see while writing/editing somewhere).
For that you'll need something like:
file=open(filename,"r+")
file.seek(0)
file.write("something" + "\n")
Well, I don't really use the "r+" method very much so I can't explain anymore. I suggest that you read more about it in the docs.
If you print str(address) to your screen, you will understand why this happens. The str command converts everything (i.e. keys and values) to a concatanated string and that will be stored in your document file.
Instead you should save the items of your address book one by one, iterating over all persons.
ok = ""
for person in address:
ok += person + " " + address[person] + "\n"
with open('addresses.txt', 'w') as file_out:
file_out.write(ok)
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).
I am trying to add a value to a list from a file, and then be able to add the values from the file to the list.
This is what I have:
L = []
def readFile(L):
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
return float(line)
L.append(line)
r.close()
def fileAddValue(L):
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a')
file = r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.sort()
r.close()
You have a few problems...
First, when you open a file you need to use with, this will handle closing your file for you.
Now, when you read each line in turn you are returning the first one. That returns from the whole function so is not what you want. I take it you want to append each item onto your list.
Also, your functions are better made generic. Pass in the filename and the data. Get them outside the function for more flexibility.
It is not clear what you want to do here. I have assumed you want to specify values to add to a list which is persisted in a file. There are better ways to do this. This is my attempt based on your original code.
def readFile(ui):
L = []
with open(ui, 'r') as f:
for line in f.readlines():
L.append(float(line))
return sorted(L)
def fileAddValue(ui, val):
with open(ui, 'a') as f:
f.write(str(val) + '\n')
ui = raw_input("Please enter your file name:")
L = readFile(ui)
print('original file:')
print(L)
val = float(raw_input("Enter the value you would like to add to the list: "))
fileAddValue(ui, val)
L = readFile(ui)
print('updated file:')
print(L)
Do you need something like that?
L = []
def readFile():
ui = input("Please enter your file name:")
r = open(ui, 'r')
files = r.readlines()
for line in files:
value = float(line)
L.append(value)
r.close()
def fileAddValue():
ui = input("Please enter your file name:")
val = float(input("Enter the value you would like to add to the list: "))
r = open(ui, 'a+')
r.write(str(val) + '\n')
for ix in r:
x = float(ix)
L.append(x)
L.append(val)
L.sort()
r.close()
if __name__ == '__main__':
readFile()
fileAddValue()
print(L)
While it's non-pytonic (tried to not touch your code unless necessary), it works if I got your question right.
Indenting code is important in Python and returning from a function guarantees that code after return will never run. If you want a function that "returns" several values so you can iterate over that "function" with for, use yield instead of return.