Ok so I am trying to have the name of the file as a raw input in python but it doesn't save to file i put in.
I get no errors, it just doesn't save to the file I write to.
For example, I run the code, I select the file that I have created and named "cops" the code runs through and accepts the input, but nothing happens. The file is still empty.
lista = {"police":"911"}
functiontext = raw_input("call function 1(save) or 2(load) ")
arguments = raw_input("input file name ")
def save(lista,arguments):
filen = arguments
spara = lista
fil = open(filen + ".txt","w")
for keys, values in spara.items():
spara_content = keys + ": " + values + "\n"
fil.write(spara_content)
fil.close()
def load(lista, arguments):
ladda = open("telefonbok.txt","r")
for namesandnumbers in ladda:
(key, val) = namesandnumbers.split(": ")
lista[(key)] = val
lista = ladda
return lista
if functiontext == 1:
save(lista,arguments)
if functiontext == 2:
load(lista, arguments)
Does anyone here have the answer to this problem?
raw_input will return a string, while you are checking for an integer comparison. Your file is not being saved because save is never being called.
if functiontext == 1:
save(lista,arguments)
if functiontext == 2:
load(lista, arguments)
Should be:
if functiontext == '1':
save(lista, arguments)
if functiontext == '2':
load(lista, arguments)
Note that you also have a typo regarding "arguements" and "arguments"
Related
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
So i'm trying to write a basic TODO list program and i'm stuck on reading the data back from my file. I managed to store the content of my list in the file but when trying to read it back i never get the result i want, i tried splitting each line, read(), readline() and then append line to my list and either i get each of my list index counted as being only index[0] or if i manage to get it working then when i add some more stuff and overwrite my file with the new list it does a completely different thing when reading the data back ..
#!/usr/bin/python3
import os
from time import sleep
import platform
import getpass
import socket
import netifaces as ni
from requests import get
toDoList = []
backup = 'TODOlist.txt'
cwd = os.getcwd()
def clean():
if platform.system() == "Linux":
os.system("clear")
else:
os.system("cls")
def printList(givenList):
i = 0
for task in givenList:
print("\n[%d]: %s" % (i, task))
i += 1
print('\n')
def addToList(listToAdd):
task = str(input("\n:"))
listToAdd.append(task)
print('\n[*]Task [%s] has been added successfully' % (task))
def removeFromList(listToRemove):
iterator = int(input("\nNumero of the task to remove :"))
removed = listToRemove[iterator]
if len(toDoList) == 1:
listToRemove.append('')
listToRemove.pop(iterator)
print("[*]\nTask [%d]: %s has been removed successfully" % (iterator, removed))
def storageFile(filename, listToStore):
overwrite = ''
if os.path.isfile(filename):
while overwrite != 'y' or overwrite != 'n':
choice = str(input('\n[!]This will overwrite your already saved list, are you sure? y/n : '))
if choice == 'y':
with open(filename, 'w+') as f:
for task in listToStore:
f.write(task)
print('[*]\nDone.')
break
else:
break
else:
with open(filename, 'w') as f:
for task in listToStore:
f.write(task)
print('\n[*]%s created in %s' % (filename, cwd))
def main():
toDoList = []
clean()
while True:
print("\n---------------Otions------------------")
print("1: Print your TODO list")
print("2: Add something")
print("3: Remove something")
print("4: Number of task in your TODO list")
print("5: Save your TODO list")
print("6: Delete all from your TODO list")
print("7: Delete existing backup of your TODO list")
print("99: Exit")
optChoice = int(input("\nChoice: "))
if optChoice == 1:
printList(toDoList)
elif optChoice == 2:
addToList(toDoList)
elif optChoice == 3:
removeFromList()
elif optChoice == 4:
print("[-]\nYour TODO list currently contains %d task(s)" % (len(toDoList)))
elif optChoice == 5:
storageFile(backup, toDoList)
elif optChoice == 6:
del toDoList[:]
print('\n[*]Done.')
elif optChoice == 7:
if os.path.isfile(backup):
os.remove(backup)
print('\n[*]Backup file %s has been removed.' % (backup))
else:
print('\n[X]No backup file has been detected')
elif optChoice == 99:
clean()
exit()
main()
Load the file:
def load(data, myPath):
with open(myPath, "r") as f: # use r for read
return [x.strip() for x in f.readlines()]
Changed your storageFile(...) to add newlines after each task:
def storageFile(filename, listToStore):
overwrite = ''
if os.path.isfile(filename):
while overwrite != 'y' or overwrite != 'n':
choice = str(input('\n[!]This will overwrite your already saved list, are you sure? y/n : '))
if choice == 'y':
with open(filename, 'w') as f:
# user a for append, w+ is not a thing
# if you switch to 'a' instead you should check for duplicates bevore
# saving: Search SO for "list to set" + "pyhton"
# else your list will double itself on saving
for task in listToStore:
f.write(task + "\n") # added a newline here
print('[*]\nDone.')
break
else:
break
else:
with open(filename, 'w') as f:
for task in listToStore:
f.write(task+ "\n") # added a newline here
print('\n[*]%s created in %s' % (filename, cwd))
Change the main a tidbit to include automatic loading on start if file present:
def main():
global toDoList # use the global one
global backup # use the global one
try:
toDoList = load(toDoList, backup)
except:
toDoList = []
clean()
while True:
# the rest of your main goes here....
If you implement a "load" in your menu you might consider checking fora already changed but not yet saved toDoList first before replacing it by whatever is in the file (ie only allow call to load if toDoList is empty or not "dirty"). You can add a isDirty = False to your globals as flag and set it to True in your addToList-function and to False when you save it.
Edit:
As to why I added the global in your main:
myvar = [1,2,3]
myOtherVar = [5,6,7]
def Test():
global myOtherVar # so in this scope "myOtherVar" == the global one
myvar = [] # shadows the global one with a local one of same name
print (myvar) # prints the local (empty) one
print(myOtherVar) # prints the global one
Test()
print("---")
print(myvar) # prints the global one (same scope, no longer shadowed)
You "shadowed" your global list with a local list of same name - by declaring it as global inside the scope of a function it will operate on the global one and not shadow it.
I wrote this script for a program I'm writing ever since I changed careers but running into a lot of issues with it. Supposed to take a string and encrypt it with a key. Not sure where to begin with troubleshooting as I'm new to programming so came here for help. Maybe if you can just point me in the write direction where to begin?
This is the error I get but looks fine.
$ python temp.py -p "ThisIsATestOfMyCode" -k "testtest"
File "encrypt.py", line 37
else:
^
This is my code.
#!/usr/bin/env python
import sys, argparse
def encrypt(varAble1, varAble2):
varAble1_size = len(varAble1)/float(len(varAble2))
if str(varAble1_size).split(".")[1] == "0":
else:
while str(varAble1_size).split(".")[1] != "0":
varAble1 +== "#"
varAble1_size = len(varAble1)/float(len(varAble2))
code = []
varAble1 = list(varAble1)
varAble2 = list(varAble2))
multiply_size = int(str((varAble1_size)).spliy(".")[0]) * 8
while varAble1 != []:
p_varAble1 = varAble1[0:8]
p_varAble2 = varAble2[0:8]
temp_list = []
for i in xrange(0,8):
if type(p_varAble2[i]) == type(int):
new_ct = (ord(chr(p_varAble2[i])) ^ ord(p_varAble1[0]))
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
code.append(new_ct)
temp_list.append(new_ct)
varAble1.pop(0)
p_varAble1.pop(0)
varAble2 = temp_list
varAble2.reverse()
code.reverse()
varAble1 = code.reverse()
code_text = []
for i in code:
hex_value = hex(i)
if len(hex_value) != 4:
code_text.append("0" + hex(i)[2:])
else:
code_text.append(hex(i)[2:])
varAble2 += i
code_text = "".join(code_text).upper()
return code_text
def main():
parser = argparse.ArgumentParser(description="Encrypt things")
parser.add_argument("-p", "--var1",help="String to enc",metavar='<pt>', required=True)
parser.add_argument("-k", "--var2", help="8 length key to encrypt with", metavar='<key>', required=True)
args = parser.parse_args()
var1 = args.var1
var2 = args.var2
hash = encrypt(var1, var2)
print "[+] Encrypted using %s [+]\n%s" % (var2, hash)
if __name__ == "__main__":
main()
The block of if str(varAble1_size).split(".")[1] == "0": is empty, so you will need to add a pass statement after it. Keef Baker is also correct in spotting that the block for else: on line 37 is not properly indented.
You have to indent your code after else :
else:
new_ct = (ord(p_varAble2[i]) ^ ord(p_varAble1[0]))
And as Andrew Kulpa noted, the block after
if str(varAble1_size).split(".")[1] == "0":
is empty, so you either need to do something in that block, or add a pass statement.
Python does not use brackets but indentation for control flow.
In your code, the Python interpreter sees an else but no statement for it, so it throws an error.
See more about control flow here : https://docs.python.org/3/tutorial/controlflow.html
import sys
import pickle
import string
def Menu():
print ("***********MENU************")
print ("0. Quit")
print ("1. Read text file")
print ("2. Display counts")
print ("3. Display statistics of word lengths")
print ("4. Print statistics to file")
def readFile():
while True:
fileName = input("Please enter a file name: ")
if (fileName.lower().endswith(".txt")):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return fileName
THE_FILE = ""
myDictionary = 0
def showCounts(fileName):
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(fileName, 'r') as f:
for line in f:
wordCount+=len(line.split())
lineCount+=1
for char in line:
if char.isdigit() == True:
numCount+=1
elif char == '.':
dotCount+=1
elif char == ',':
commaCount+=1
print("Number count: " + str(numCount))
print("Comma count: " + str(commaCount))
print("Dot count: " + str(dotCount))
print("Line count: " + str(lineCount))
print("Word count: " + str(wordCount))
def showStats(fileName):
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(fileName, 'r') as f:
for line in f:
words = line.split()
for word in words:
temp2.append(word)
temp1.append(len(word))
for x in temp1:
if x not in lengths:
lengths.append(x)
lengths.sort()
dictionaryStats = {}
for x in lengths:
dictionaryStats[x] = []
for x in lengths:
for word in temp2:
if len(word) == x:
dictionaryStats[x].append(word)
for key in dictionaryStats:
print("Key = " + str(key) + " Total number of words with " + str(key) + " characters = " + str(len(dictionaryStats[key])))
return dictionaryStats
def printStats(aDictionary):
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
choice = -1
while choice !=0:
Menu()
choice = (int(input("Please choose 1-4 to perform function. Press 0 to exit the program. Thank you. \n")))
if choice == 0:
print ("Exit program. Thank you.")
sys.exit
elif choice == 1:
THE_FILE = readFile()
elif choice == 2:
showCounts(THE_FILE)
elif choice == 3:
showStats(THE_FILE)
elif choice == 4:
printStats(myDictionary)
else:
print ("Error.")
I'm trying to open a file, have it display the statistics of the word lengths, and then have it make a new file with the statistics of the word lengths. I can read the file and have it display the statistics, but when I print the statistics to file I get an error - "int" object is not iterable. Any ideas? Thanks guys!
Error:
Traceback (most recent call last):
File "hw4_ThomasConnor.py", line 111, in <module>
printStats(myDictionary)
File "hw4_ThomasConnor.py", line 92, in printStats
for key in aDictionary:
TypeError: 'int' object is not iterable
The problem is that you set myDictionary to 0 at the top of your program, and then are sending it to your file writing function here printStats(myDictionary).
In this function you have this line for key in aDictionary, and since you passed in 0, this is effectively for key in 0 which is where the error comes from.
You need to send the result of the showStats function to your printStats function.
As this is looking like homework, I will leave it at that for now.
Sorry I am confused. in the showStats function I have to somehow say
"send results to printStats function" and then in the printStats
function I have to call the results? How would I do that exactly?
The printStats function is expecting a dictionary to print. This dictionary is generated by the showStats function (in fact, it returns this dictionary).
So you need to send the result of the showStats function to the printStats function.
To save the return value of a method, you can assign it on the LHS (left hand side) of the call expression, like this:
>>> def foo(bar):
... return bar*2
...
>>> def print_results(result):
... print('The result was: {}'.format(result))
...
>>> result = foo(2) # Save the returned value
Since result is just like any other name in Python, you can pass it to any other function:
>>> print_results(result)
The result was: 4
If we don't want to store the result of the function, and just want to send it to another function, then we can use this syntax:
>>> print_results(foo(2))
The result was: 4
You need to do something similar in your main loop where you execute the functions.
Since the dictionary you want to print is returned by the showStats function, you must call the showStats function first before calling the printStats function. This poses a problem if your user selects 4 before selecting 3 - make sure you find out a work around for this. A simple work around would be to prompt the user to calculate the stats by selecting 3 before selecting 4. Try to think of another way to get around this problem.
Here:
THE_FILE = ""
myDictionary = 0
you set integer to myDictionary.
and later you do:
printStats(myDictionary)
and as you try to interate over keys of dictionary inside, you fail.
I'm writing a function that prompts for input and then returns different results based on the input and then asks for input again. I've got it returning the correct values, but I'm not sure how to make it prompt for input again.
Here's the actual code of the function:
def interact():
command = raw_input('Command:')
command = command.split(' ')
if command[0] == 'i':
bike_name = command[1] + ' ' + command[2]
return get_product_id(products, bike_name)
if command [0] == 'n':
return get_product_name(products, command[1])
if command[0] == 'c':
return compute_cost(products, part, command[1])
if command[0] == 'p':
return get_parts(products, command[1])
In each line with return in it, it is simply calling up a previously defined function. The products and part are dictionaries, defined previously.
I can only use the builtin functions.
I would do it with a while loop. Like This:
while True:
com = raw_input('Command:').split()
if len(com) == 0:
break
elif com[0] == 'i':
bike_name = command[1] + ' ' + command[2]
return get_product_id(products, bike_name)
You've done most of the work, you just need this:
while True:
print interact()
There is no need to take so much pain and write your own command line interpreter.
Look at this: http://docs.python.org/2/library/cmd.html
One way is to put it in a while loop, and then also check for an exit input to break out.
Call the method inside an (end-less) loop:
while True:
some_method()