1

I my python GUI, I have created a questionaire. In this it allows me to ask questions and then save them to a text file. i have saved them to a text file using a variable, so each file is different. E.G.

name = james (the file will be called james)

or...

name = Charlie (the file will be called Charlie)

I am able to write and save to the text file. What I need to b able to do is find a way to open the text file by using a variable. this will allow me to input a name, such as "James" and I can open the file called James.

This is the code I have at the moment.

name = entry.get()       
     # this collects the name from an entry box.
newfile = (name.txt,"r")    
     # name is the variable I am using.
loaded = (newfile.read())
     # this would hopefully put the file text into a variable
textbox.delete(0.0, END)
     # this will clear the text box
textbox.insert(END, loaded) 
     # this put the text from the file (in loaded) into the text box

Is there a way to allow me to do this? I hope this makes sense. Thank you all who help.

1 Answer 1

3

First, you're not calling open anywhere. Just writing, e.g., (path, "r") doesn't give you a file object, it just gives you a tuple of two strings.

Second, literal strings have to be in quotes. And if you want to concatenate two strings, it doesn't matter whether they're in variables or literals, that's just +.

So:

newpath = name + ".txt"
newfile = open(newpath, "r")

Also, while you're at it, you should close the file somewhere. Ideally by using a with statement:

newpath = name + ".txt"
with open(newpath, "r") as newfile:
    loaded = newfile.read()
Sign up to request clarification or add additional context in comments.

1 Comment

ok, that makes sence. thank you very much!! i will tick when i can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.