Trying to write a string to a tempfile - python

I'm making a game of 20 questions. In the code I've created a tempfile to keep track of the user's questions. Here's the code:
import random
import turtle
import tempfile
import gzip
def getAnswer():
obj = random.randrange(5)
if obj == 0:
infile1 = open("appleyes.txt", "r")
infile2 = open("applecanbe.txt", "r")
answer = "apple"
elif obj == 1:
infile1 = open("dogyes.txt", "r")
infile2 = open("dogcanbe.txt", "r")
answer = "dog"
elif obj == 2:
infile1 = open("carrotyes.txt", "r")
infile2 = open("carrotcanbe.txt", "r")
answer = "carrot"
elif obj == 3:
infile1 = open("flyyes.txt", "r")
infile2 = open("flycanbe.txt", "r")
answer = "fly"
elif obj == 4:
infile1 = open("caryes.txt", "r")
infile2 = open("carcanbe.txt", "r")
answer = "car"
print(answer)
return infile1, infile2, answer
def startAsking(infile1, infile2):
count = 1
tfile = tempfile.TemporaryFile()
while count <= 20:
ask = input("Is it/Does it have: ")
if ask.isalpha():
if ask.lower() in tfile:
print("You've already asked this.\n")
else:
with gzip.open(tfile+".gz","wb") as f_out:
f_out.write(bytes(ask, 'UTF-8'))
if ask.lower() in infile1.split():
print("Yes it is/Yes it could\n")
count = count + 1
elif ask.lower() in infile2.split():
print("It can be/It could\n")
count = count + 1
else:
print("No or not sure\n")
count = count + 1
else:
print("No numbers or symbols please.\n")
infile1.close()
infile2.close()
tfile.close()
def guessingTime(answer):
print("That's 20! Time to guess.\n")
guess = eval(input("Is it a(n): "))
if guess.lower() == answer:
print("You got it! Congratulations!\n")
else:
print("Sorry, but the answer was\n")
def main():
infile1, infile2, answer = getAnswer()
startAsking(infile1, infile2)
guessingTime(answer)
main() `#Brian Reser H787A975
#Python Project
#Program plays 20 questions with the user. It randomly pulls a text file for the answer and keeps track of the user's answers.
import random
import turtle
import tempfile
import gzip
def getAnswer():
obj = random.randrange(5)
if obj == 0:
infile1 = open("appleyes.txt", "r")
infile2 = open("applecanbe.txt", "r")
answer = "apple"
elif obj == 1:
infile1 = open("dogyes.txt", "r")
infile2 = open("dogcanbe.txt", "r")
answer = "dog"
elif obj == 2:
infile1 = open("carrotyes.txt", "r")
infile2 = open("carrotcanbe.txt", "r")
answer = "carrot"
elif obj == 3:
infile1 = open("flyyes.txt", "r")
infile2 = open("flycanbe.txt", "r")
answer = "fly"
elif obj == 4:
infile1 = open("caryes.txt", "r")
infile2 = open("carcanbe.txt", "r")
answer = "car"
print(answer)
return infile1, infile2, answer
def startAsking(infile1, infile2):
count = 1
tfile = tempfile.TemporaryFile()
while count <= 20:
ask = input("Is it/Does it have: ")
if ask.isalpha():
if ask.lower() in tfile:
print("You've already asked this.\n")
else:
with gzip.open(tfile+".gz","wb") as f_out:
f_out.write(bytes(ask, 'UTF-8'))
if ask.lower() in infile1.split():
print("Yes it is/Yes it could\n")
count = count + 1
elif ask.lower() in infile2.split():
print("It can be/It could\n")
count = count + 1
else:
print("No or not sure\n")
count = count + 1
else:
print("No numbers or symbols please.\n")
infile1.close()
infile2.close()
tfile.close()
def guessingTime(answer):
print("That's 20! Time to guess.\n")
guess = eval(input("Is it a(n): "))
if guess.lower() == answer:
print("You got it! Congratulations!\n")
else:
print("Sorry, but the answer was\n")
def main():
infile1, infile2, answer = getAnswer()
startAsking(infile1, infile2)
guessingTime(answer)
main()
The error comes along when it reaches the part where it writes the string "ask" to the tempfile. How do I fix this?
TypeError: unsupported operand type(s) for +: '_TemporaryFileWrapper' and 'str'

The problem is that tfile is a file object and not a string. Fix it by doing something like this:
filename = tfile.name
fullfilename = filename + ".gz"
gzip.open(fullfilename,"wb")
See http://docs.python.org/2/library/tempfile.html for details.

Related

I'm getting IndexError: list index out of range when I know the index is within range

I'm getting the IndexError on line 50 (the sixth line of checkForDisallowedCharacters while j < len(resultSet[i]):)
I get this error when I input '***er', 't', and 'canpilru' into the console when prompted
Using my print statements I've found that this error occurs when the resultSet array has a length of 141, and when i is 0
resultSet[0] is 'paper' and it clearly exists
If anyone can explain why this is throwing an error I would be very grateful
import csv
import os
import sys
def buildDictionary():
dictionary = []
with open("./wordle-helper/wordle-dictionary.csv", newline='') as csvfile:
spamreader = csv.reader(csvfile, delimiter='\t')
for row in spamreader:
dictionary.append(row)
for i in range(len(dictionary)):
dictionary[i] = dictionary[i][0].lower()
return dictionary
def buildTestWordComposition(testWord):
testWordComposition = []
for i in range(len(testWord)):
if testWord[i] == "*":
testWordComposition.append(i)
return testWordComposition
def buildThreshold(testWord):
threshold = 0
for character in testWord:
if character != "*":
threshold += 1
return threshold
def checkForSoftMatches(dictionary, testWord, threshold):
resultSet = []
for word in dictionary:
testThreshold = 0
for i in range(5):
if testWord[i] == "*":
continue
elif testWord[i] == word[i]:
testThreshold += 1
if testThreshold == threshold:
resultSet.append(word)
return resultSet
def checkForDisallowedCharacters(resultSet, disallowedCharacters):
i = 0
while i < len(resultSet):
print(len(resultSet), i, resultSet[i][0])
j = 0
while j < len(resultSet[i]):
for character in disallowedCharacters:
if resultSet[i][j] == character:
try:
resultSet.remove(resultSet[i])
finally:
i -= 1
j = -1
break
j += 1
i += 1
if i < 0:
i = 0
elif i >= len(resultSet):
break
return resultSet
def checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition):
resultSetChecked = []
threshold = len(requiredCharacters)
m = 0
resultSetCheckedLength = 0
while m < len(resultSetNoDisallowedCharacters):
compareToThreshold = 0
for aCharacter in requiredCharacters:
for number in testWordComposition:
if resultSetNoDisallowedCharacters[m][number] == aCharacter:
compareToThreshold += 1
break
if len(resultSetChecked) != resultSetCheckedLength:
break
if compareToThreshold == threshold:
resultSetChecked.append(resultSetNoDisallowedCharacters[m])
resultSetCheckedLength = len(resultSetChecked)
m += 1
return resultSetChecked
def wordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
dictionary = buildDictionary()
testWordComposition = buildTestWordComposition(testWord)
threshold = buildThreshold(testWord)
resultSet = checkForSoftMatches(dictionary, testWord, threshold)
resultSetNoDisallowedCharacters = checkForDisallowedCharacters(resultSet, disallowedCharacters)
resultSetChecked = checkForRequiredCharacters(resultSetNoDisallowedCharacters, requiredCharacters, testWordComposition)
if not resultSetChecked:
return resultSetNoDisallowedCharacters
return resultSetChecked
def printWordleHelper(testWord, requiredCharacters=[], disallowedCharacters=[]):
print("All possible words are listed below\n\n-----------------------------------------------\n")
for word in wordleHelper(testWord, requiredCharacters, disallowedCharacters):
print(word)
def handlePersistentCharacters(disallowedCharactersComplete):
willDisallowedCharactersPersist = input("Would you like to continue using your previous list of grey letters? (y/n): ")
if willDisallowedCharactersPersist == "y":
return disallowedCharactersComplete
elif willDisallowedCharactersPersist == "n":
return []
else:
print("Please enter a valid character")
handlePersistentCharacters(disallowedCharactersComplete)
def clearConsole():
if sys.platform.startswith('linux') or sys.platform.startswith('darwin'):
os.system('clear')
elif sys.platform.startswith('win'):
os.system('cls')
def buildParsed(unparsed):
parsed = []
for letter in unparsed:
parsed.append(letter)
return parsed
def handleUserContinue(disallowedCharactersComplete):
willUserContinue = input("Would you like to use World Helper (tm) again? (y/n): ")
if willUserContinue == "n":
sys.exit()
persistentDisallowedCharacters = handlePersistentCharacters(disallowedCharactersComplete)
if willUserContinue == "y":
promptUser(persistentDisallowedCharacters)
def promptUser(persistentDisallowedCharacters=[]):
clearConsole()
testWord = input("Please enter your Wordle guess in the form of *la*t where 'l', 'a', and 't' are the green letters from your guess, and the '*'s are yellow or grey letters from your guess: ")
requiredCharacters = input("Please enter your letters in yellow here in the form of 'abcxyz' (do not enter letters which are already in your Wordle guess string): ")
disallowedCharacters = input("Please enter your letters in grey here (in the form of 'abcxyz'): ")
requiredCharactersParsed = buildParsed(requiredCharacters)
disallowedCharactersParsed = buildParsed(disallowedCharacters)
disallowedCharactersComplete = persistentDisallowedCharacters + disallowedCharactersParsed
printWordleHelper(testWord, requiredCharactersParsed, disallowedCharactersComplete)
handleUserContinue(disallowedCharactersComplete)
promptUser()

I am getting an error if acc[0] == var[0]: TypeError: 'NoneType' object is not subscriptabl. how do I fix this?

I am writing a car rental program on python.
In this function I am trying to modify car details which are added in the details.txt file but I am getting an error "if acc[0] == var[0]:TypeError:'NoneType' object is not subscriptable"
how do I fix this error ?
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
count += 1
mod_file.close()
if exist != True:
print("!!! Can NOT Find The Data !!!")
elif exist == True:
s_list = []
mod_file = open("details.txt", "r")
for s in mod_file:
s = s.strip()
s_list.append(s)
mod_file.close
choice = "Y"
while choice == "Y":
print("\n===============================")
print("---------- MODIFY Cars ----------")
print("---------------------------------")
print("Select the details you wish to modify")
print("1. Type")
print("2. Manufactured Year")
print("3. details of the car")
print("4. car code")
print("5. Daily price rate ( USD $ )")
print("6. back")
while True:
try:
c = int(input("please select a number (1 - 5): "))
modify = ["Type", "Manufactured Year", "details of the car", "car code", "Daily price rate ( USD $ )"]
if c > 0 and c < 6:
new = input("\nType the New " + modify[c - 1] + ":")
var[c - 1] = new
temp = ",".join(var)
s_list[count] = temp
mod_file = open("details.txt", "w")
mod_file.write("")
mod_file.close()
count_file = 0
for s in range(len(s_list)):
mod_file = open("details.txt", "r")
for counting in mod_file:
count_file += 1
mod_file.close()
mod_file = open("details.txt", "a")
if count_file == 0:
mod_file.write(s_list[s])
else:
mod_file.write("\n")
mod_file.write(s_list[s])
mod_file.close()
print("\nDetails UPDATED")
be_exit = input("\nDo you want to modify again? (Y/N): ").upper()
if be_exit == "y":
choice = "y"
else:
modifying(acc)
elif c == 6:
modifying(acc)
else:
print("\n!!! Incorrect Input !!!\n")
continue
except:
print("\n!! NOT a Number !!!\n")
continue
modifying()
You have to do
acc = some_value
def modifying():
global acc
exist = False
mod_file = open("details.txt")
count = 0
for s in mod_file:
var = s.split(",") # spilt the data into list
var[2] = var[2].strip()
if acc[0] == var[0]:
exist = True
break
In your example you haven't defined the variable acc. Using global just say that the variable is a global variable, but you're not assigning a value to it

Is there a command for exiting and re-entering a script?

Sorry for the other post, it had an error.
My simplified code:
#test
import json
x = {}
x['x'] = {'y': 1, 'z': 0}
with open('x.json', 'w') as f:
json.dump(x, f)
and
#test2
import json
f = open('x.json')
x = json.load(f)
while x['x']['y'] > 0:
x['x']['z'] = x['x']['z'] + 1
x['x']['y'] = x['x']['y'] - 1
if x['x']['y'] == 0:
print(x['x']['z'])
n = input("Number: ")
while n.isdigit() == False:
print("Not a number")
n = input("Number: ")
if n.isdigit() == True:
x['x']['y'] = int(n)
with open('x.json', 'w') as f:
json.dump(x, f)
I have two codes so I don't overwrite the numbers of test2 with test
This is already kinda what I want, but my output for n = 4 and n = 5 is:
1
Number: 4
5
Number: 5
10
Number:
And so on...
But instead, I want the code to Exit completely and then start it again without me doing it manually. Kinda like:
1
Number: 4
Code restarts
5
Number: 5
Code restarts
5
Number: 10
and so on. Thank you :-)
If I understood you correctly , You will have to create two separate scripts
test1.py
#test
import json
import os
x = {}
x['x'] = {'y': 1, 'z': 0}
with open('x.json', 'w') as f:
json.dump(x, f)
os.system('python test2.py') # this line will run the second script
test2.py
import json
f = open('x.json')
x = json.load(f)
while x['x']['y'] > 0:
x['x']['z'] = x['x']['z'] + 1
x['x']['y'] = x['x']['y'] - 1
if x['x']['y'] == 0:
print(x['x']['z'])
n = input("Number: ")
while n.isdigit() == False:
print("Not a number")
n = input("Number: ")
if n.isdigit() == True:
x['x']['y'] = int(n)
with open('x.json', 'w') as f:
json.dump(x, f)

Python file appears to be empty after a function

Code:
import os, csv
def menu():
print("Welcome to da sporty ting" + "\n" + "Menu options: " + "\n")
print("1 - Run the code")
print("2 - Exit")
menu_choice = int(input("Enter choice: "))
while menu_choice not in (1, 2):
menu_choice = int(input("Error, try again: "))
if menu_choice == 1:
finding_file()
elif menu_choice == 2:
exit()
def finding_file():
print("\n")
print("Text file options" + "\n")
print("1 - testfile 1" + "\n" + "2 - testfile 2" + "\n" + "3 - Other")
txt_menu_option = int(input("Enter choice: "))
print("\n")
while txt_menu_option not in (1, 2, 3):
txt_menu_option = input(input("Error, try again: "))
if txt_menu_option == 1:
filename = "Test1_Votes.txt"
pass
elif txt_menu_option == 2:
filename = "Test2_Votes.txt"
pass
elif txt_menu_option == 3:
filename = str(input("Enter name of txt file (don't include .txt at he end) : "))
filename = filename + ".txt"
file_exists = os.path.exists(filename)
if file_exists == False:
print("File does not exist, returning to menu")
menu()
pass
file_validity(filename)
def file_validity(filename):
f = open(filename, 'r+') # opening file in read/write mode
inv_lines_cnt = 0
valid_list = [0, 0, 1, 2, 3] # sorted list of valid values
lines = f.read().splitlines()
f.seek(0)
f.truncate(0) # truncating the initial file
for l in lines:
if sorted(map(int, l.split(','))) == valid_list:
f.write(l + '\n')
else:
print(l + " is a invalid line")
inv_lines_cnt += 1
print("There were {} invalid line/lines.".format(inv_lines_cnt))
calculate_quota(filename)
def calculate_quota(filename):
f = open(filename, 'r+')
lines = f.readlines()
print("Calculate quota " + str(lines))
seats = 2
line_count = 0
for line in lines:
line_count += 1
quota = 0
quota == int((line_count / (seats + 1)) + 1)
print(quota)
quota_required(quota, lines)
def quota_required(quota, lines):
for line in lines:
lines.rstrip(',')
lines.rstrip('\n')
print(lines)
candidate_fp_votes = [0,0,0,0,0]
for line in lines:
for i in range(5):
if line[i] == 1:
print ("if working")
candidate_fp_votes[i] += 1
print (candidate_fp_votes)
print (candidate_fp_votes)
Text file sample:
1,2,3,0,0
0,0,3,2,1
1,0,0,3,2
1,0,0,2,3
0,1,2,3,0
Currently I have a problem where after file_validity(), the text file just appears to have loaded up as empty as when I re-open the file in the next function, it prints lines as empty. file_validity() just deletes the file, and rewrites the valid votes. As you can see I have tried to find out where the trouble lies. I believe the truncate and seek functions seem to be causing some trouble but I am not sure if this is true. And if it were to be the case, how to fix it.
Any help?
Thanks in advance.

Python - print value to new file?

import sys
import pickle
import string
def Menu():
print ("\n***********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 Loop():
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:
user_File = ReadTextFile()
elif choice == 2:
DisplayCounts(user_File)
elif choice == 3:
DisplayStats(user_File)
elif choice == 4:
PrintStats(aDictionary)
else:
print ("Error.")
def ReadTextFile():
print "\n"
while True:
InputFile = input("Please enter a file name (NOTE: must have quotation marks around name and extension): ")
if (InputFile.lower().endswith('.txt')):
break
else:
print("That was an incorrect file name. Please try again.")
continue
return InputFile
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, '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 DisplayStats(InputFile):
print "\n"
temp1 = []
temp2 = []
lengths = []
myWords = []
keys = []
values = []
count = 0
with open(InputFile, '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):
print "\n"
aFile = open("statsWords.dat", 'w')
for key in aDictionary:
aFile.write(str(key) + " : " + str(aDictionary[key]) + "\n")
aFile.close()
Loop()
There's something with that last function that is really tripping me up. I keep getting errors. I know aDictionary is not defined but I do not even know what to define it as! Any of you guys have an idea? Thanks.
with open("some_file.txt","W") as f:
print >> f, "Something goes here!"
its hard to say without your errors. .. but you almost certainly need to have aDictionary defined
also probably something like
def DisplayCounts(InputFile):
print "\n"
numCount = 0
dotCount = 0
commaCount = 0
lineCount = 0
wordCount = 0
with open(InputFile, '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
return dict(numbers=numCount,
comma=commaCount,
dot=dotCount,
line=lineCount,
word=wordCount)
result = DisplayCounts("someinput.txt")
print result

Categories

Resources