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
Related
I am attempting to create a loop that creates a file named "/tmp/newfile.txt" and creates 29 lines of text. Line 1 should read: "I see 0 sheep". For each line, 1 sheep should be added and a new line created to reflect that until 29 sheep (and lines) are reached.
x = 0
myDoc = myDoc.readfiles("/tmp/newfile.txt", "r+")
myDoc.write("I see" + str(x) + "sheep")
for line in myDoc.readfiles():
x = x + 1
myDoc.append(x)
print(myDoc)
if x == 30
break;
First, what I tried to do is create a new file and put it into a variable (myDoc) that would open it. I specified w+ so that I would have the ability to read the file and write on it. I gave the changing number a variable 'x'.
The function I intended to, for each line in the file, write "I see x sheep". Afterward, add 1 to the current value of x and append it so it's added to the file. After this, print it so I can see the line(s). Once that value reached 30, cease the loop because 29 is the number of lines I need.
My errors have to do with indentation and nothing being printed at all. I am extremely new to this.
Welcome to StackOverflow!
There seem to be a couple of issues in the code:
Indentation / Syntax Errors - It seems that you are using Python, which follows strict indentation and whitespace rules. An indent is inserted when you enter a new local scope / new control flow / enter an if/elif/else statement or a while or for loop, to separate it from the current scope.
You'd need to remove the space on the left side on line 3 and line 6.
Also, on line 8 there should be a colon(:) after the if x==30.
The mode used (w+) isn't going to work as expected.
This mode overwrites a file if it already exists and allows you to read and write to that file. Instead, you would need the r+ mode.
There's a great explanation & flowchart in this answer explaining the various file modes - https://stackoverflow.com/a/30566011/13307211
The for loop can't iterate over myDoc.
The open function gives a file object (TextIOWrapper), which can't be iterated over. You could use the myDoc.readfiles() method, which returns a list of lines present in the file and loop over that - for line in myDoc.readfiles().
printing myDoc and using .append() with myDoc wouldn't work as expected. It's representing a file object, which doesn't have an append method. Also, I feel like there might have been some mixed logic here - were you trying to iterate over myDoc like an array and hence pushing value to it?
I'd suggest removing the append part as the past value of x isn't going to be needed for what you want to do.
After applying the above, you should end up with code that looks like this -
x = 0
myDoc = open("./newfile.txt", "r+")
for line in myDoc.readlines():
myDoc.write("I see" + str(x) + "sheep\n")
x = x + 1
if x == 30:
break
Now, this doesn't exactly do what you want it to do...
The first thing we should do is update the for loop - a for loop should be structured in a way where it has a start, an end, and an increment, or it should iterate over a range of values. Python has a neat range function that allows you to iterate between values.
for x in range(1, 10):
print(x)
the above would print values from 1 to 10, excluding 10.
updating our for loop, we can change the code to -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep")
we could also use a while loop here -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep")
this makes the file but without the lines and without the right formatting. "I see " + str(x) + " sheep" should fix the sentence, but to print the string on multiple lines instead of the same line, you would need to use the newline character(\n) and add it at the end of the string -
myDoc = open("./newfile.txt", "r+")
for x in range(1, 30):
myDoc.write("I see" + str(x) + "sheep\n")
So I'm still new to coding and I've got a mess of for loops, conditional if statements, and a couple of while loops. My code loops over files and depending on my input, it moves the files to a location matching my input. However, I would like to be able to prompt the code to simply print a list but not move onto the next file. I've tried placing it into a while loop but whenever the while loop is satisfied, it passes onto the next file.
while True:
try:
if "print df" in answer:
subset_folders_list = list()
for folder in all_folders_list:
if folder.startswith('A'):
subset_folders_list.append(folder)
df = pd.DataFrame(subset_folders_list, columns ['Folders'])
print(df)
But upon an input of "print-folders", it will print my dataframe and move onto the next file because the condition of the while loop is met. How can I get this code to print this dataframe without moving onto the next file. Note that this while loop is nested inside of another while loop inside of a function that is called inside of another loop that is inside of a function. But I think this is the only chunk of code I need to fix in order to implement this feature.
EDIT: other relevant code:
for filename in files_to_move:
counter += 1
matching_folders = list()
iterating = True
item_words = set(re.split('[. ,_-]', filename.lower()))
source_file_path = os.path.join(paths[0], filename)
all_folders_list = [g for g in os.listdir(paths[12]) if not g.startswith('.')]
#Matching the filename with a folder
for folder in all_folders_list:
count = 0
folder_words = folder.lower().split(' ')
for word in item_words:
if word in folder_words:
count += 1
if count >= 2:
matching_folders.append(folder)
#Multiple matching folders
if len(matching_folders) >= 2:
print("\n" + f"There is MORE than one folder for {filename}")
if not filename in files_to_move:
continue
while iterating:
try:
pass
answer_2 = input("\n" + f"MOVE IT TO ONE OR ELSEWHERE (type name of folder or print-subset for subset list)?: ")
item_words = answer_2.lower().split(' ')
if len(item_words) >= 2:
#Moving file to a matching or input folder
for folder in all_folders_list:
count = 0
folder_words = folder.lower().split(' ')
for word in item_words:
if word in folder_words:
count += 1
if count == 2:
folder_path = os.path.join(paths[12], folder)
destination_file_path = os.path.join(folder_path, filename)
shutil.move(source_file_path, destination_file_path)
print("\n" + f"File moved to {folder}")
print(FTG)
iterating = False
break
if len(item_words) < 2:
file_mover(source_file_path, paths, filename, answer_2, iterating, all_folders_list, matching_folders, x, counter)
iterating = False
break
So my function file_mover() has many other conditional if statements in it, I will skip them because they work, but the part I want to add is to be able to print the subset without moving onto the next file. Here is file_mover:
def file_mover(source_file_path, paths, filename, answer_2, iterating, all_folders_list, matching_folders, x, counter):
FTG = str("\n" + str(x - counter) + " files to go")
while iterating:
if "exit" in answer_2:
print()
iterating = False
sys.exit()
if "pass" in answer_2:
print("Moving on to NEXT file" + "\n")
print(FTG)
iterating = False
pass
if "del" in answer_2:
shutil.move(source_file_path, os.path.join(paths[15], filename))
print(f"File moved to DELETE folder" + "\n")
print(FTG)
iterating = False
#This is where I want the ability to just print something given the input "print-subset", or something like that, and have it re-prompt me for an input.
else:
break
The reason I want to add this is because there is a subset of non-matching folders that sometimes I want to move the files to, and I don't always remember what they are or I type them in wrong. Now I've got an error catcher in my main while loop, so that could easily function as a workaround for typing in the folder name wrong, but I'm new to coding and this would be good practice. I've tried a lot of things and I can get it to print over and over again endlessly or I can get it to print one time but it moves onto the next file. I don't want either of those to happen. I'd like the subset to print once and have it prompt me for an input again for the same file. I can also try to implement this in the len(item_words) >= 2 section and do the input as "print subset", but I might also run into the same problems.
I need this program to create a sheet as a list of strings of ' ' chars and distribute text strings (from a list) into it. I have already coded return statements in python 3 but this one keeps giving
return(riplns)
^
SyntaxError: invalid syntax
It's the return(riplns) on line 39. I want the function to create a number of random numbers (randint) inside a range built around another randint, coming from the function ripimg() that calls this one.
I see clearly where the program declares the list I want this return() to give me. I know its type. I see where I feed variables (of the int type) to it, through .append(). I know from internet research that SyntaxErrors on python's return() functions usually come from mistype but it doesn't seem the case.
#loads the asciified image ("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
#creates a sheet "foglio1", same number of lines as the asciified image, and distributes text on it on a randomised line
#create the sheet foglio1
def create():
ref = open("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
charcount = ""
field = []
for line in ref:
for c in line:
if c != '\n':
charcount += ' '
if c == '\n':
charcount += '*' #<--- YOU GONNA NEED TO MAKE THIS A SPACE IN A FOLLOWING FUNCTION IN THE WRITER.PY PROGRAM
for i in range(50):#<------- VALUE ADJUSTMENT FROM WRITER.PY GOES HERE(default : 50):
charcount += ' '
charcount += '\n'
break
for line in ref:
field.append(charcount)
return(field)
#turn text in a list of lines and trasforms the lines in a list of strings
def poemln():
txt = open("/home/gcg/Documents/Programmazione/Python projects/imgascii/writer/poem")
arrays = []
for line in txt:
arrays.append(line)
txt.close()
return(arrays)
#rander is to be called in ripimg()
def rander(rando, fldepth):
riplns = []
for i in range(fldepth):
riplns.append(randint((rando)-1,(rando)+1)
return(riplns) #<---- THIS RETURN GIVES SyntaxError upon execution
#opens a rip on the side of the image.
def ripimg():
upmost = randint(160, 168)
positions = []
fldepth = 52 #<-----value is manually input as in DISTRIB function.
positions = rander(upmost,fldepth)
return(positions)
I omitted the rest of the program, I believe these functions are enough to get the idea, please tell me if I need to add more.
You have incomplete set of previous line's parenthesis .
In this line:-
riplns.append(randint((rando)-1,(rando)+1)
You have to add one more brace at the end. This was causing error because python was reading things continuously and thought return statement to be a part of previous uncompleted line.
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()]
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.