Passwords/username from a file - python

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()]

Related

Reading from and printing records from a file

I need to be able to read from a file and print records if a variable entered is pre-existent in the file. I have tried to open the file as 'f' however that would only read the first line in the file, heres my code:
problem = input("Please select from one of these: sink, faucet, toilet, shower, heater, other: \n")
temporaryFile = open("plumberInfo.txt" , "r")
for row in temporaryFile:
record = row.split(",")
if record[6] == problem:
Pforename = record[1]
Psurname = record[2]
Pfee = record[3]
Pexperience = record[4]
Prate = record[5]
print("You have selected", Pforename, Psurname, "they have", Pexperience , "years of experience and they specialise in", problem, "\n")
else:
print("Invalid input")
plumberSearch() #This part isn't relevant
Also below I have attached some contents of the file:
743,Auryn,Smith,42.00,6,44.50,faucet,extra
583,Michael,Lanlow,25.00,8,75.00,sink,extra
731,Hanna,Taylor,42.00,14,55.00,heater,extra
981,Tomie,Agen,32.00,6,44.50,toilet,extra
I don't understand the problem as it worked fine for when I was searching by the ID ([record0]). There is no traceback error, it just states invalid input which means record[6] != problem, however it is equal.
When I try the code on my machine, printing record shows me that the last item contains a new line character at the end. Thus when you search for sink, you're essentially doing the search sink == sink\n, hence why you get invalid input.
Reading in the file also reads in the new line, and you need to be aware. You would need to remove it before doing the comparison.

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

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.

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

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.

Restricting the User Input to Alphabets

I'm a technical writer learning python. I wanted to write a program for validating the Name field input,as a practise, restricting the the user entries to alphabets.I saw a similar code for validating number (Age)field here, and adopted it for alphabets as below:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
print raw_input("Your Name:")
x = r
if x == r:
print x
elif x != r:
print "Come on,'", x,"' can't be your name"
print raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
I intend this code block to do two things. Namely, display the input prompt until the user inputs alphabets only as 'Name'. Then, if that happens, process the length of that input and display messages as coded. But, I get two problems that I could not solve even after a lot of attempts. Either, even the correct entries are rejected by exception code or wrong entries are also accepted and their length is processed.
Please help me to debug my code. And, is it possible to do it without using the reg exp?
If you're using Python, you don't need regular expressions for this--there are included libraries which include functions which might help you. From this page on String methods, you can call isalpha():
Return true if all characters in the string are alphabetic and there is at least one character, false otherwise.
I would suggest using isalpha() in your if-statement instead of x==r.
I don't understand what you're trying to do with
x = r
if x == r:
etc
That condition will obviously always be true.
With your current code you were never saving the input, just printing it straight out.
You also had no loop, it would only ask for the name twice, even if it was wrong both times it would continue.
I think what you tried to do is this:
import string
import re
r = re.compile(r'[a-zA-Z]+')
print "WELCOME FOR NAME VERIFICATION. TYPE ALPHABETS ONLY!"
x = raw_input("Your Name:")
while not r.match(x):
print "Come on,'", x,"' can't be your name"
x = raw_input("Your Name:")
if 5<=len(x)<=10:
print "Hi,", x, "!"
elif len(x)>10:
print "Mmm,Your name is too long!"
elif len(x)<5:
print "Alas, your name is too short!"
raw_input("Press 'Enter' to exit!")
Also, I would not use regex for this, try
while not x.isalpha():
One way to do this would be to do the following:
namefield = raw_input("Your Name: ")
if not namefield.isalpha():
print "Please use only alpha charactors"
elif not 4<=len(namefield)<=10:
print "Name must be more than 4 characters and less than 10"
else:
print "hello" + namefield
isalpha will check to see if the whole string is only alpha characters. If it is, it will return True.

Categories