How can i write this function that mostly prints to a file? - python

So I posted about another part of this code yesterday but I've run into another problem. I made a character generator for an RPG and im trying to get the program the output of a character sheet function to a .txt file, but i think whats happening is that the function may return a Nonevalue for some of the stats (which is totally normal,) and then i get an error because of that when i try to write to a .txt file. I'm totally stumped, and help would be vastly appreciated!
# Character Sheet Function.
def char_shee():
print "Name:", name
print "Class:", character_class
print "Class Powers:", class_power
print "Alignment:", alignment
print "Power:", pow, pow_mod()
print "Intelligence:", iq, iq_mod()
print "Agility:", agi, agi_mod()
print "Constitution:", con, con_mod()
print "Cynicism:", cyn, cyn_mod()
print "Charisma:", cha, cha_mod()
print "All Characters Start With 3 Hit Dice"
print"""
\t\t{0}'s History
\t\t------------------
\t\tAge:{1}
\t\t{2}
\t\t{3}
\t\t{4}
\t\t{5}
\t\t{6}
\t\t{7}
\t\t{8}
\t\t{9}
\t\tGeneral Disposition: {10}
\t\tMost important thing is: {11}
\t\tWho is to blame for worlds problems: {12}
\t\tHow to solve the worlds problems: {13}
""".format(name, age, gender_id, ethnic_pr, fcd, wg, fogo_fuck, cur_fam,fam_fuk, nat_nur, gen_dis, wha_wor, who_pro, how_pro)
char_shee()
print "Press enter to continue"
raw_input()
# Export to text file?
print """Just because I like you, let me know if you want this character
saved to a text file. Please remember if you save your character not to
name it after something important, or you might lose it.
"""
text_file = raw_input("Please type 'y' or 'n', if you want a .txt file")
if text_file == "y":
filename = raw_input("\nWhat are we calling your file, include .txt")
target = open(filename, 'w')
target.write(char_shee()
target.close
print "\nOk I created your file."
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
else:
print """
Thanks so much for using the Cyberpanky N.O.W Character Generator
By Ray Weiss
Goodbye
"""
EDIT: Here is the output i get:
> Please type 'y' or 'n', if you want a .txt filey
>
> What are we calling your file, include .txt123.txt <function char_shee
> at 0x2ba470> Traceback (most recent call last): File "cncg.py", line
> 595, in <module>
> target.write(pprint(char_shee)) TypeError: must be string or read-only character buffer, not None

Using print writes to sys.stdout, it doesn't return a value.
You you want char_shee to return the character sheet string to write it to a file, you'll need to just build that string instead.
To ease building the string, use a list to collect your strings:
def char_shee():
sheet = []
sheet.append("Name: " + name)
sheet.append("Class: " + character_class)
# ... more appends ...
# Return the string with newlines
return '\n'.join(sheet)

you forgot parenthesis here:
target.write(char_shee())
target.close()
and as #Martijn Pieters pointed out you should return value from char_shee(), instead of printing them.

Related

My program can't write output in a file in the expected format

I'm working through a few coding problems on this website I found. To my understanding, what the website does to check whether my program is outputting the expected results is that it makes me write the output on a new file line by line, and then it compares my file with the file that contains the answers. I'm trying to submit my solution for a problem and keep getting the following error message:
> Run 1: Execution error: Your program did not produce an answer
that was judged as correct. The program stopped at 0.025 seconds;
it used 9360 KB of memory. At character number 7, your answer says
'<Newline>' while the correct answer says ' '.
Here are the respective outputs:
----- our output ---------
mitnik_2923
Poulsen_557
Tanner_128
Stallman_-311
Ritchie_-1777
Baran_245
Spafford_-1997
Farmer_440
Venema_391
Linus_-599
---- your output ---------
mitnik
_2923Poulsen
_557Tanner
_128Stallman
_-311Ritchie
_-1777Baran
_245Spafford
_-1997Farmer
_440Venema
_391Linus
_-599
--------------------------
I'm pretty sure my program outputs the expected results, but in the wrong format. Now, I've never written stuff on files using Python before, and therefore don't know what I'm supposed to change to get my output in the proper format. Can someone help me? Here's my code:
fin = open ('gift1.in', 'r')
fout = open ('gift1.out', 'w')
NP,d=int(fin.readline()),dict()
for _ in range(NP):
d[fin.readline()]=0
for _ in range(NP):
giver=fin.readline()
amt,ppl=list(map(int,fin.readline().split()))
if ppl==0 or amt==0:sub=-amt;give=0
else:sub=amt-(amt%ppl);give=amt//ppl
d[giver]-=sub
for per in range(ppl):
d[fin.readline()]+=give
for i in d: ##I'm doing the outputting in this for loop..
ans=str(i)+' '+str(d[i])
fout.write(ans)
fout.close()
The line returned by find.readline() includes the trailing newline. You should strip that off before using it as the dictionary key. That's why you see a newline after all the names.
fout.write() doesn't add a newline after the string you're writing, you need to add that explicitly. That's why there's no newline between the number and the next name.
with open ('gift1.in', 'r') as fin:
NP = int(fin.readline())
d = {fin.readline().strip(): 0 for _ in range(NP)}
for _ in range(NP):
giver=fin.readline().strip()
amt, ppl= map(int,fin.readline().split())
if ppl==0 or amt==0:
sub=-amt
give=0
else:
sub=amt-(amt%ppl)
give=amt//ppl
d[giver]-=sub
for per in range(ppl):
d[fin.readline().strip()]+=give
with open ('gift1.out', 'w') as fout:
for i in d: ##I'm doing the outputting in this for loop..
ans= i + " " + str(d[i])+'\n'
fout.write(ans)
Other points:
Don't cram multiple assignments onto the same line unnecessarily. And no need to put the if and else all on 1 line.
i is a string, there's no need to use str(i)
Use a context manager when opening files.

Passwords/username from a file

I've recently been having trouble writing a program that involves taking the password and username from a .txt file. So far I have written:
username_file = open("usernameTest1.txt","rt")
name = username_file.readlines()
username_file.close()
print(username_file)
print(name)
print(name[0])
print()
print(name[1])
Player1Name = name[0]
print(Player1Name)
nametry = ""
while nametry != (name[0]):
while True:
try:
nametry = input("What is your Username player1?: ")
break
except ValueError:
print("Not a valid input")
(The various prints are to help me to see what the error is)
The password is successfully extracted from the file however when it is put into a variable and put through an if statement, it doesn't work!
Any help would be much appreciated!
Hopefully this is a simple fix!
Your problem is that readlines() function lets the \n character remain in your text lines and that causes the texts to not match. You can use this instead when opening the file:
name = username_file.read().splitlines()
give it a try.
the readlines function doen't strip the newline character from the end of the lines, so eventough you wrote "samplename" as input, it won't equal "samplename\n".
You can try this:
name = [x.rstrip() for x in username_file.readlines()]

python3 looping a list with 1 variable at a time

still learning python, so I apologize if this question is sloppy.
I am familiar with loops, and looping through a file. However, I have not found the correct referance to looping a file, storing the variable and calling that variable into another function, and maintain the increment.
Using pyautogui and pywinauto.
Written form:
get names.txt file with list of 20 or so names (the list changes so keeping track of line count seems reasonable)
Split the text of the file for parsing.
in example:
setup of name.txt file.
Mark
James
Sam
Steve
.
def do(name):
# open and read file
fname = 'names.txt'
for name in (open(fname, "r")).readlines():
print("Found: " + name)
more(name)
Output:
['Mark', 'James', 'Sam', 'Steve]
def more(name):
pyautogui.moveT0(600,511)
pyautogui.click()
pyautogui.typewrite(a[0])
pyautogui.moveTo(699,412)
pyautogui.press("enter")
confirm(name)
def confirm(name)
pic = pyscreenshot.grab(bbox=(8,11,211,728))
f = "images/active"
g = "images/go"
pic.save(f + a + ".png")
pic.save(g + ".png")
b = Image.open("images/go.png"
text = image_to_search(b, lang='eng')
if text == name:
print("Success")
else:
print("Mismatch")
This is the part where the function will end and start back at the top of the program increment our digit and applying the next name for searching. The confirm program (already completed) takes an image of the search field and passes the text. If the name is equal to the name in the list (a[0]) then we move onto the next name.
Bringing up another question of how to "call a variable from a function"?
Thanks a lot!
First off, your code is rife with indentation, syntactical and logcial errors, you have to fix those before you apply the below
def file_stuff(a, fname):
for name in (open(fname, "r")).readlines():
print ("Found: " + name)
gui_stuff(name)
def gui_stuff(name):
pyautogui.moveT0(600,511)
pyautogui.click()
pyautogui.typewrite(name) # ATTENTION, please confirm if this is how the typewriter fn works. you are only printing the first char
pyautogui.moveTo(699,412)
pyautogui.press("enter")
confirm(name)
Please fix the if-else indentation in your confirm function, and other dangling indentation references in your code

Please correct my code Python

I am trying to read from a file and return solutions based on the problem that the user inputs. I have saved the text file in the same location, that is not an issue. At the moment, the program just crashes when I run it and type a problem eg "screen".
Code
file = open("solutions.txt", 'r')
advice = []
read = file.readlines()
file.close()
print (read)
for i in file:
indword = i.strip()
advice.append (indword)
lst = ("screen","unresponsive","frozen","audio")
favcol = input("What is your problem? ")
probs = []
for col in lst:
if col in lst:
probs.append(col)
for line in probs:
for solution in advice:
if line in solution:
print(solution)
The text file called "solutions.txt" holds the following info:
screen: Take the phone to a repair shop where they can replace the damaged screen.
unresponsive: Try to restart the phone by holding the power button for at least 4 seconds.
frozen: Try to restart the phone by holding the power button for at least 4 seconds.
audio: If the audio or sound doesnt work, go to the nearest repair shop to fix it.
Your question reminds me a lot of my learning, so I will try give an answer to expand on your learning with lots of print statements to consider how it works carefully. It's not the most efficient or stable approach but hopefully of some use to you to move forwards.
print "LOADING RAW DATA"
solution_dictionary = {}
with open('solutions.txt', 'r') as infile:
for line in infile:
dict_key, solution = line.split(':')
print "Dictionary 'key' is: ", dict_key
print "Corresponding solution is: ", solution
solution_dictionary[dict_key] = solution.strip('\n')
print '\n'
print 'Final dictionary is:', '\n'
print solution_dictionary
print '\n'
print 'FINISHED LOADING RAW DATA'
solved = False
while not solved: # Will keep looping as long as solved == False
issue = raw_input('What is your problem? ')
solution = solution_dictionary.get(issue)
""" If we can find the 'issue' in the dictionary then 'solution' will have
some kind of value (considered 'True'), otherwise 'None' is returned which
is considered 'False'."""
if solution:
print solution
solved = True
else:
print ("Sorry, no answer found. Valid issues are 'frozen', "
"'screen' 'audio' or 'unresponsive'")
want_to_exit = raw_input('Want to exit? Y or N? ')
if want_to_exit == 'Y':
solved = True
else:
pass
Other points:
- don't use 'file' as a variable name anywhere. It's a python built-in and can cause some weird behaviour that you'll struggle to debug https://docs.python.org/2/library/functions.html
- If you get an error, don't say "crashes", you should provide some form of traceback e.g.:
a = "hello" + 2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-6f5e94f8cf44> in <module>()
----> 1 a = "hello" + 2
TypeError: cannot concatenate 'str' and 'int' objects
your question title will get you down-votes unless you are specific about the problem. "help me do something" is unlikely to get a positive response because the error is ambiguous, there's no sign of Googling the errors (and why the results didn't work) and it's unlikely to be of any help to anyone else in the future.
Best of luck :)
When I change the line "for i in file:" to "for i in read:" everything works well.
To output only the line starting with "screen" just forget the probs variable and change the last for statement to
for line in advice:
if line.startswith( favcol ) :
print line
break
For the startswith() function refer to https://docs.python.org/2/library/stdtypes.html#str.startswith
And: the advices of roganjosh are helpfull. Particularly the one "please don't use python keywords (e.g. file) as variable names". I spent hours of debugging with some bugs like "file = ..." or "dict = ...".

replacing text in a file, Python

so this piece of code is meant to take a line from a file and replace the certain line from the string with a new word/number, but it doesn't seem to work :(
else:
with open('newfile', 'r+')as myfile:
x=input("what would you like to change: \nname \ncolour \nnumber \nenter option:")
if x == "name":
print("your current name is:")
test_lines = myfile.readlines()
print(test_lines[0])
y=input("change name to:")
content = (y)
myfile.write(str.replace((test_lines[0]), str(content)))
I get the error message TypeError: replace() takes at least 2 arguments (1 given), i don't know why (content) is not accepted as an argument. This also happens for the code below
if x == "number":
print ("your current fav. number is:")
test_lines = myfile.readlines()
print(test_lines[2])
number=(int(input("times fav number by a number to get your new number \ne.g 5*2 = 10 \nnew number:")))
result = (int(test_lines[2])*(number))
print (result)
myfile.write(str.replace((test_lines[2]), str(result)))
f=open('newfile', 'r')
print("now we will print the file:")
for line in f:
print (line)
f.close
replace is a function of a 'str' object.
Sounds like you want to do something like (this is a guess not knowing your inputs)
test_lines[0].replace(test_lines[0],str(content))
I'm not sure what you're attempting to accomplish with the logic in there. looks like you want to remove that line completely and replace it?
also i'm unsure what you are trying to do with
content = (y)
the output of input is a str (which is what you want)
EDIT:
In your specific case (replacing a whole line) i would suggest just reassigning that item in the list. e.g.
test_lines[0] = content
To overwrite the file you will have to truncate it to avoid any race conditions. So once you have made your changes in memory, you should seek to the beginning, and rewrite everything.
# Your logic for replacing the line or desired changes
myfile.seek(0)
for l in test_lines:
myfile.write("%s\n" % l)
myfile.truncate()
Try this:
test_lines = myfile.readlines()
print(test_lines[0])
y = input("change name to:")
content = str(y)
myfile.write(test_lines[0].replace(test_lines[0], content))
You have no object known purely as str. The method replace() must be called on a string object. You can call it on test_lines[0] which refers to a string object.
However, you may need to change your actual program flow. However, this should circumvent the error.
You need to call it as test_lines[0].replace(test_lines[0],str(content))
Calling help(str.replace) at the interpreter.
replace(...)
S.replace(old, new[, count]) -> str
Return a copy of S with all occurrences of substring
old replaced by new. If the optional argument count is
given, only the first count occurrences are replaced.
Couldn't find the docs.

Categories