Reputation: 23
I'm doing a simple program that moves files, and I'm having it pull the file paths from a text document so it doesn't have to be inputed every time.
Here's the function for one of the buttons:
def XboxClick():
pathfinder = open("settings.txt", "r")
xboxsavepath = pathfinder.readline()
steamsavepath = pathfinder.readline()
pathfinder.close
#lbl.configure(text=xboxsavepath)
xboxsavefile = filedialog.askopenfilename(title="Select the Xbox save", initialdir=xboxsavepath)
In the text document, this row is C:/Users/username/AppData/Local/Packages/
.
The commented out line #lbl.configure(text=xboxsavepath)
will return C:/Users/username/AppData/Local/Packages/
.
If I do:
xboxsavefile = filedialog.askopenfilename(title="Select the Xbox save", initialdir='C:/Users/username/AppData/Local/Packages/')
It will open the file window at that directory.
However, when using the variable xboxsavepath
, which uses the exact same string, it just opens the file window to the default. I don't know why.
Hopefully that's enough info.
Upvotes: 2
Views: 1511
Reputation: 15098
The reason was quite hard to spot, but it is because there is a newline character at the end of your string because you are using readline
.
From the docs:
f.readline()
reads a single line from the file; a newline character (\n) is left at the end of the string....
If you want to see the newline(\n) then do something like print(repr(xboxsavepath))
. So, strip the text that you get from the file so the newline character will be removed
xboxsavepath = pathfinder.readline().strip()
It is also better to strip all the lines you get from the txt, so even if there is an empty line at the end, you don't have to worry about it
You also need pathfinder.close()
with the ()
to execute the method.
Upvotes: 2