I have very complicated problem. I´ve search whole internet and tried everything, but nothing worked. I want get string from listbox and than delete line in file with word from listbox. Can please somebody help me? Here is code:
def OnDelete(self, event):
sel = self.listbox.GetSelection()
if sel != -1:
self.listbox.Delete(sel)
subor = open("Save/savegame.txt", "r")
lines = subor.readlines()
subor.close()
subor = open("Save/savegame.txt", "w")
selstring = self.listbox.GetString(self.listbox.GetSelection())
for line in lines:
if line!=selstring:
subor.write(line)
subor.close()
And this is code for saving file:
def OnNewGame(self,event):
nameofplr = wx.GetTextFromUser('Enter your name:', 'NEW GAME')
subor=open("Save/savegame.txt","a")
subor.write( "\n" + nameofplr)
subor.close()
savegame=open("Save/" + nameofplr + ".prjct", "w+")
savegame.close()
It shows this error:
Traceback (most recent call last):
File "D:\Python\Python Projects\Project\Project.py", line 106, in OnDelete
selstring = self.listbox.GetString(self.listbox.GetSelection())
File "D:\Python\lib\site-packages\wx-3.0-msw\wx_core.py", line 12962, in GetString
return core.ItemContainer_GetString(*args, **kwargs)
wx._core.PyAssertionError: C++ assertion "IsValid(n)" failed at ....\src\msw\listbox.cpp(387) in wxListBox::GetString(): invalid index in wxListBox::GetString
Thank you very much for help!
Think about how your program works:
In the OnDelete method you check which item is selcted, then you delete this item. Then you do something with your file. After that you try to get the string from your selected item, but this was deleted by you.
You should call Delete after the line
selstring = self.listbox.GetString(self.listbox.GetSelection())
It would also be nice if you would put your code in a code block, so that we can see the indentation.
Than you very much! I have fixed it! If somebody will have the same problem you must change OnDelete code (The first code in question) for this:
def OnDelete(self, event):
sel = self.listbox.GetSelection()
f = open("Save/savegame.txt", "r")
read = f.readlines()
f.close()
name = self.listbox.GetStringSelection()
newfile = """"""
for i in read:
if name in i:
pass
else:
newfile += i
n = open("Save/savegame.txt", "w")
one = str(newfile)
n.write(one)
n.close
self.listbox.Delete(sel)
Related
I have two functions. The first one is used to get a list of paths to text files, and the second one is used to iterate over this list of paths and then check if they include the word password. But because of the Try Except statement in the second function, I had to use recursion to make it continue running unless there's another way if possible to provide below. My problem is that the list returned in the second function is empty why and how to fix it?
def search_txt():
"""Function to search the C:\\ for .txt files -> then add them (including full path to file) to a list."""
list_of_txt = []
for dir_path, sub_dir, files in os.walk("C:\\"):
"""Method 1 -> checks the end of the file name (could be used for specific extensions)"""
for file in files:
if file.endswith(".txt"):
list_of_txt.append(os.path.join(dir_path, file))
return list_of_txt
def search_pass_file(list_of_files: list):
"""Function to iterate over each text file, searching if the word "password" is included -> Returns the text
file's path """
list_of_pass = []
if len(list_of_files) != 0:
for i in range(len(list_of_files)):
file = list_of_files.pop()
try:
with open(file, encoding="utf8") as f:
for line in f.readlines():
if "password" in line:
list_of_pass.append(file)
except UnicodeDecodeError:
return search_pass_file(list_of_files)
except PermissionError:
return search_pass_file(list_of_files)
else:
return list_of_pass
if __name__ == '__main__':
myList = search_txt()
print(search_pass_file(myList))
You're returning list_of_pass only if len(list_of_files) == 0 (it's in the else block). Your return statement should occur after the loop (which should be a while one btw)
You can except several errors in one line by putting them in parenthesis: except (UnicodeDecodeError, PermissionError) of except all exceptions (for instance, you're not handling FileNotFoundError).
I'd reduce your function to:
def search_pass_file(list_of_files: list):
"""Function to iterate over each text file, searching if the word "password" is included -> Returns the text
file's path """
list_of_pass = []
while list_of_files:
file = list_of_files.pop()
try:
with open(file, encoding="utf8") as f:
for line in f.readlines():
if "password" in line:
list_of_pass.append(file)
break
except Exception:
list_of_pass += search_pass_file(list_of_files)
return list_of_pass
Edit: also in your except block, you should append the returned value of the recursive function to list_of_pass otherwise you'll lose the files found after the error occurs.
So i have a problem with this code, it doesnt like embeds. It will automaticly delete any embeds from other bots. Is there anyway to stop this from happening.
#client.event
async def on_message(msg):
if msg.author == client.user:
return
with open('BadWords.txt', 'r') as f:
BadWords = f.readlines()
for line in BadWords:
if msg.content in line:
await msg.delete()
await client.process_commands(msg)
Thanks for the help in advance
This most likely happens because you have an empty line in your .txt file, which means that Python matches the empty string with the empty content. You have a few options... for clarity I include the surrounding code
You can check if the specific line is empty
for line in BadWords:
if line == '':
continue
if msg.content in line:
Or you can remove it before you start looping
BadWords = f.readlines()
try:
BadWords.remove('')
except ValueError:
pass
Lastly it's also possible you ignore the message if it has no content, as this can also happen if someone sends a file or attachment.
if msg.author == client.user:
return
if msg == '':
return
Apologies if this is a repost. I am trying to write a while loop with a continue variable and if/else statement. My issue is that my continue variable is being ignored I cannot find the problem thus far. So far I have moved the while continues == 'y' condition into the else block now I am a bit flummoxed on why this var is being overlooked.
code:
def add_to_existing_file(data):
# data[0]-api response
# data[1]-city
# infile-file object returned from openFile()
# file_name- file name string. check filetype & report version.
continues = 'y' # set up continue variable
while continues == 'y':
file_name = input("Enter File Path to file to be appended: ") # get file from user
if file_name is False:
print("Now Creating Excel File..") # create condition for no user response.
return # if empty response exit function
else:
infile = appends.openFile(file_name) # open file to work with. Returns file object.
added_data = appends.journal_report_1_to_df(infile, file_name, data[0], data[1]) # append selected file to existing df
continues = input("Do you want to append another file? Y or N").lower() # check if new file
return added_data # return new df w/appended data
The problem happens on the last line. You're returning at the end of the first iteration, which exits the loop. This can be fixed by moving the return to the outer scope.
def add_to_existing_file(data):
# data[0]-api response
# data[1]-city
# infile-file object returned from openFile()
# file_name- file name string. check filetype & report version.
continues = 'y' # set up continue variable
while continues == 'y':
file_name = input("Enter File Path to file to be appended: ") # get file from user
if file_name is False:
print("Now Creating Excel File..") # create condition for no user response.
return # if empty response exit function
else:
infile = appends.openFile(file_name) # open file to work with. Returns file object.
added_data = appends.journal_report_1_to_df(infile, file_name, data[0], data[1]) # append selected file to existing df
continues = input("Do you want to append another file? Y or N").lower() # check if new file
return added_data # return new df w/appended data
It should work if you get the second return line (return added_data # return new df w/appended data) to have the same indentation as your while line. As a basic outline for a continue loop:
def function
continues = 'y'
while
if :
elif :
else :
print
continue ?
return
def readfile(filename,mode="rt"):
head = "<li><a href="""
center =""" target="_blank">"""
end ="<br></a></li>"
with open(filename,mode) as fin:
for line in fin:
link = line
length_link = len(link)
twitter_name_after = link[twitter_name_before+5:]
full_code = head+link+center+"#"+twitter_name_after+end
writefile("C:/Users/Johny The Overlord/Documents/Code/test_1.txt",full_code)
def writefile(filename,contents,mode="wt"):
with open(filename,mode) as fout:
fout.write(contents)
def main():
# my code here
readfile("C:/Users/Johny The Overlord/Documents/Code/test.txt")
if __name__ == "__main__":
main()
url in text1 https://twitter.com/xxx https://twitter.com/yyy
https://twitter.com/zzz
in text2 should have https://twitter.com/xxx
target="_blank">#xxx https://twitter.com/yyy
target="_blank">#yyy https://twitter.com/zzz
target="_blank">#zzz
but it only write last url.
how do I fix?
I think it is just because of writing mode. Try using "a" or"a+" to amend have a look here https://stackoverflow.com/a/23051095/3759158
You can overwrite the previous one, try to write it (i mean in write function) in separate lines.
Add fout.write("\n") to your write functions after fout.write(contents)
How come it's not opening the file I put into the function? It opens when I plug the file name directly into the main program, but not when I try to pass it through the function. It gives me a FileNotFoundError.
def get_valid_filename(prompt):
'''Use prompt (a string) to ask the user to type the name of a file. If
the file does not exist, keep asking until they give a valid filename.
Return the name of that file.'''
filename = input(prompt)
if os.path.isfile(filename) == False:
print ("That file does not exist.")
filename = input(prompt)
return filename
if __name__ == '__main__':
prompt = 'enter the name of the file with unknown author:'
mystery_filename = get_valid_filename(prompt)
# readlines gives us the file as a list of strings each ending in '\n'
text = open(mystery_filename, 'r').read()
print (text)
get_valid_filename should look like this:
def get_valid_filename(prompt):
while True:
filename = input(prompt):
if os.path.exists(filename):
return filename
print('that file does not exist')