The below def is working perfectly in cmd, but when writing to the file, it is only writing the second data.write statement. The first statement is definitely working, it is just not writing. Given the code is identical i can't figure out for the life of me what is wrong.
def follower_count(list1):
for name in list1:
name = '#' + name
try:
user = api.get_user(name)
if user.followers_count < 5000:
print ""
print "FAILED TEST"
print name
print user.followers_count
data.write(name + ": " + user.followers_count + "\n")
else:
print ""
print name
print user.followers_count
except:
print ""
print "Error grabbing " + name
data.write("Error Grabbing: " + name + "\n")
return()
data.write(name + ": " + user.followers_count + "\n")
This line will crash with TypeError: Can't convert 'int' object to str implicitly if user.followers_count is an integer.
Try using str.format to interpolate your strings.
data.write("{}: {}\n".format(name, user.followers_count))
Furthermore, you're making debugging much harder for yourself by not displaying any diagnostic information in your except. You know that an error occurred, but don't know anything about that error specifically. At the very least, you could do:
except Exception as e:
print ""
print "Error grabbing " + name
data.write("Error Grabbing: " + name + "\n")
data.write(e.message + "\n")
Which will at least tell you what the error message is.
Related
I have this function that prints 25 lines of text and I need to input it in my tkinter page, but ever time it doesn't seem to work.
I've tried using text.input but it didn't seeem to work
This is the function I need to print:
def decode(secretmessage):
for key in range(len(alphabet)):
newAlp = alphabet[key:] + alphabet[:key]
attempt = ""
for i in range(len(message)):
index = alphabet.find(message[i])
if index < 0:
attempt += message[i]
else:
attempt += newAlp[index]
print("Key: " + str(key) + " - " + attempt)
print()
This is what I tried:
def finalprint (uncoded):
print("Key: " + str(key) + " - " + attempt)
print()
text = Text.insert(root, finalprint(message), width=450, height=450)
It doesn't work to show up for some reason.
The print command prints the given text to console. It does returns None
Your finalprint function also returns None while Text.insert expects a string as an input.
Instead of printing the output you can store the values into a string.
def finalprint(uncoded): ## may need different inputs as key and attempts are not in scope
string = ""
string = string + "Key: " + str(key) + " - " + attempts + "\n"
return string
However the input to the finalprint function is uncoded while the variables used in it are key and attempts. You may need to pass in more information to the function for it to work like you have it written.
a program to store information about a single user. The program should include a function that asks the user for their name, age, course, and home town and stores this in memory. It should also have a function that will write the information entered in a file. Use exception handling to protect the data entry and the file operations
really stuck on this any help would be great
name=raw_input("Enter name :")
surname=raw_input("Enter surname :")
n=None
while n is None:
age=raw_input("Enter age :")
try:
n = int(age)
except ValueError:
print "Not a number."
course=raw_input("Enter course :")
hometown=raw_input("Enter hometown :")
with open("workfile","w") as f:
f.write('Name : ' + name + '\n')
f.write('Surname : ' + surname + '\n')
f.write('Age : ' + str(age) + '\n')
f.write('Course : ' + course + '\n')
f.write('Hometown : ' + hometown + '\n')
f.close()
for exception handling in file I/O see What is a good way to handle exceptions when trying to read a file in python?
I am making a simple Text Based File System. Anyhow I am having trouble when printing out all three parts to my File System. In the File System there are three parts, the Name, Date, and Text. The Name is the file's name, the Date is the date the file was written on, and the Text is the file's contents. Now when I am appending the Name, Date, and Text to the files dictionary I can not get the Text to print out. Below is the code I am using to append the three variables to the dictionary.
files[filename] = {filedate:filetext}
Then I am using the following code to print out each of the values. (Only the Name and Date will print out)
for filename in files:
print "--------------------------------------------"
print "File Name: " + str(filename)
for filedate in files[filename]:
print "File Date: " + str(filedate)
for filetext in files.values():
print "File Contents: " + str(filetext)
I am not sure why it won't work correctly. Below is my full code so far.
import datetime
import time
files = {}
# g = open('files.txt', 'r')
# g.read(str(files))
# g.close()
def startup():
print "\n ------------------- "
print " FILE SYSTEM MANAGER "
print " ------------------- "
print "\n What would you like to do with your files?"
print " To make a new file type in: NEW"
print " To edit a current file type in: EDIT"
print " Tp delete a current file type in: DELETE"
print " To view all current files type in: ALL"
print " To search a specific file type in: SEARCH"
chooser = raw_input("\n Please enter NEW, EDIT, DELETE, ALL, or SEARCH: ")
if chooser.lower() == "new":
newfile()
elif chooser.lower() == "edit":
editfiles()
elif chooser.lower() == "delete":
deletefiles()
elif chooser.lower() == "all":
allfiles()
elif chooser.lower() == "search":
searchfiles()
else:
startup()
#-- New File -------------------------------
def newfile():
filename = ""
filetext = ""
while filename == "":
print "--------------------------------------------"
filename = raw_input("\n Please input your new files name: ")
while filetext == "":
filetext = raw_input("\n Please input the text for your new file: ")
filedate = datetime.date.today()
files[filename] = {filedate:filetext}
# f = open ('files.txt', 'w')
# f.write(str(files))
# f.close()
print "\n File Added"
print "\n--------------------------------------------"
print "\n ------------------- "
print " FILE SYSTEM MANAGER "
print " ------------------- "
print "\n What would you like to do with your files?"
print " To make a new file type in: NEW"
print " To edit a current file type in: EDIT"
print " Tp delete a current file type in: DELETE"
print " To view all current files type in: ALL"
print " To search a specific file type in: SEARCH"
chooser = raw_input("\n Please enter NEW, EDIT, DELETE, ALL, or SEARCH: ")
if chooser.lower() == "new":
newfile()
elif chooser.lower() == "edit":
editfiles()
elif chooser.lower() == "delete":
deletefiles()
elif chooser.lower() == "all":
allfiles()
elif chooser.lower() == "search":
searchfiles()
else:
startup()
def editfiles():
pass
def deletefiles():
pass
def allfiles():
for filename in files:
print "--------------------------------------------"
print "File Name: " + str(filename)
for filedate in files[filename]:
print "File Date: " + str(filedate)
for filetext in files.values():
print "File Contents: " + str(filetext)
def searchfiles():
pass
startup()
P.S. If you're feeling extra nice, I am trying to get the file writing to work correctly. The parts where I have tried to write it to a file are commented out. I am not exactly sure how to write to a file, but I gave it a shot. I am writing to the files.txt file, and I want it to save the file dictionary, and open it every time the program is closed.
Besides that the structure you use is VERY weird, you should replace
for filetext in files.values():
with
for filetext in files[filename].values():
I would rather use namedtuple to represent file record though.
Part of your problem is that files.values() enumerates the outer dict values (where you were placing dicts representing individual files), not the text for a given file. I am perplexed because it should have printed the entire dict - I can't explain why it didn't print anything. Nominally, you could fix it with for filetext in files[filename].values(), but you can also get key, value in one fell swoop and reduce the number of lookups:
for filename, content in files.iteritems():
print "--------------------------------------------"
print "File Name: " + str(filename)
for filedate, text in content.iteritems():
print "File Date: " + str(filedate)
print "File Contents: " + str(filetext)
I have this file system that I am trying to get to work. My problem so far is when printing out all of the files. I can get the name to print out, but then I do not know how to access the date and text.
My Full Code
import datetime
import time
files = {}
# g = open('files.txt', 'r')
# g.read(str(files))
# g.close()
def startup():
print "\n ------------------- "
print " FILE SYSTEM MANAGER "
print " ------------------- "
print "\n What would you like to do with your files?"
print " To make a new file type in: NEW"
print " To edit a current file type in: EDIT"
print " To view all current files type in: ALL"
print " To search a specific file type in: SEARCH"
chooser = raw_input("\n Please enter NEW, EDIT, ALL, or SEARCH: ")
if chooser.lower() == "new":
newfile()
elif chooser.lower() == "edit":
editfiles()
elif chooser.lower() == "all":
allfiles()
elif chooser.lower() == "search":
searchfiles()
else:
startup()
#-- New File -------------------------------
def newfile():
filename = ""
filetext = ""
while filename == "":
print "--------------------------------------------"
filename = raw_input("\n Please input your new files name: ")
while filetext == "":
filetext = raw_input("\n Please input the text for your new file: ")
filedate = datetime.date.today()
files[filename] = {filedate:filetext}
# f = open ('files.txt', 'w')
# f.write(str(files))
# f.close()
print "\n File Added"
print "\n--------------------------------------------"
print "\n ------------------- "
print " FILE SYSTEM MANAGER "
print " ------------------- "
print "\n What would you like to do with your files?"
print " To make a new file type in: NEW"
print " To edit a current file type in: EDIT"
print " To view all current files type in: ALL"
print " To search a specific file type in: SEARCH"
chooser = raw_input("\n Please enter NEW, EDIT, ALL, or SEARCH: ")
if chooser.lower() == "new":
newfile()
elif chooser.lower() == "edit":
editfiles()
elif chooser.lower() == "all":
allfiles()
elif chooser.lower() == "search":
searchfiles()
else:
startup()
def editfiles():
pass
def allfiles():
for i in files:
print "--------------------------------------------"
print "File Name: " + str((i))
for i[filedate] in files:
print "File Date: " + (i[filedate])
def searchfiles():
pass
startup()
It works correctly and prints the name of each file with this:
for i in files:
print "--------------------------------------------"
print "File Name: " + str((i))
then after that I can't seem to access the date and text.
I am saving the dictionaries to the dictionary file like this:
files[filename] = {filedate:filetext}
The code I am using to try to get the filedate is this:
for i in files:
print "--------------------------------------------"
print "File Name: " + str((i))
for i[filedate] in files:
print "File Date: " + (i[filedate])
and the error it gives me is >> NameError: global name 'filedate' is not defines
EDIT
how would I also add the filetext to the for loop for it to print?
THANK YOU
First off, you are iterating through the dictionary, and by default only the keys are returned, so when you do
for i in files:
Only the keys (names of the files) are stored in i, so i[filedate] would return nothing even if filedate was defined. You need to use dict.items() for both cases, which return both the key and value as pairs. Correcting your code, it will become this:
def allfiles():
for filename, filevalue in files.items():
print "--------------------------------------------"
print "File Name: " + filename
for filedate, filetext in filesvalue.items():
print "File Date: " + filedate
for a_date in files[i]:
print "File Date: " + a_date
I think would work fine ...
it becomes much more clear if you change your variable names
def allfiles():
for fileName in files:
print "--------------------------------------------"
print "File Name: " + fileName
for a_date in files[fileName]:
print "File Date: " + a_date
filedate is only defined in the function newfile(). If you want to be able to use it in the function allfiles() then you either need to re-declare it there or make the variable global.
I'm writing a simple program to help generate orders for a game I'm a member of. It falls into the catergory of programmes I don't actually need. But now I've started I want it to work. It all pretty much runs smoothly but I can't figure out how to stop a type-error ocurring about half way through. Here's the code;
status = 1
print "[b][u]magic[/u][/b]"
while status == 1:
print " "
print "would you like to:"
print " "
print "1) add another spell"
print "2) end"
print " "
choice = input("Choose your option: ")
print " "
if choice == 1:
name = raw_input("What is the spell called?")
level = raw_input("What level of the spell are you trying to research?")
print "What tier is the spell: "
print " "
print "1) low"
print "2) mid"
print "3) high"
print " "
tier = input("Choose your option: ")
if tier == 1:
materials = 1 + (level * 1)
rp = 10 + (level * 5)
elif tier == 2:
materials = 2 + (level * 1.5)
rp = 10 + (level * 15)
elif tier == 3:
materials = 5 + (level * 2)
rp = 60 + (level * 40)
print "research ", name, "to level ", level, "--- material cost = ",
materials, "and research point cost =", rp
elif choice == 2:
status = 0
Can anyone help?
edit
The error I get is;
Traceback (most recent call last):
File "C:\Users\Mike\Documents\python\magic orders", line 27, in <module>
materials = 1 + (level * 1)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
A stacktrace would've helped, but presumably the error is:
materials = 1 + (level * 1)
‘level’ is a string, and you can't do arithmetic on strings. Python is a dynamically-typed language, but not a weakly-typed one.
level= raw_input('blah')
try:
level= int(level)
except ValueError:
# user put something non-numeric in, tell them off
In other parts of the program you are using input(), which will evaluate the entered string as Python, so for “1” will give you the number 1.
But! This is super-dangerous — imagine what happens if the user types “os.remove(filename)” instead of a number. Unless the user is only you and you don't care, never use input(). It will be going away in Python 3.0 (raw_input's behaviour will be renamed input).
Here is an example of a Type Error and how to fix it:
# Type Error: can only concatenate str (not "int") to str
name = "John"
age = 30
message = "My name is " + name + " and I am " + age + " years old."
# Fix:
message = "My name is " + name + " and I am " + str(age) + " years old."
In the above example, the error message says that we're trying to concatenate a string and an integer which is not possible. So, we need to convert the integer to string using str() function to fix the error.