mathgeniuszach / xdialog

A cross-platform wrapper for native dialogs written entirely in python.
MIT License
21 stars 3 forks source link

xdialog changes current working directory of script when opening or saving files #8

Closed my1e5 closed 1 year ago

my1e5 commented 1 year ago

Consider this minimal example

import xdialog, os

TEST_FILENAME = "test.txt"

if os.path.exists(TEST_FILENAME):
    os.remove(TEST_FILENAME)

xdialog.open_file()

with open(TEST_FILENAME, "w") as f:
    f.write("Hello World")

If I open a file using xdialog then with open(....) as f: f.write doesn't work as expected, test.txt isn't created in the working directory the python script was run from. It is created in the last directory xdialog accessed.

If I cancel the dialog instead of opening a file, then it works correctly and text.txt is created in the working directory the python script was run from.

The same happens with save_file.

In my DPG application, I was wondering why files weren't saving in my main working directory and why this only happened when I opened a file with xdialog. Turns out they were saving to the last location I opened a file from.

OS: Windows 10 Python: 3.10.0 xdialog 1.0.9.0

my1e5 commented 1 year ago

I note that using the tkinter filedialog this doesn't happen. I can open a file from any directory and the with open(filename)... creates the file in the directory the python script was run from (rather than the last directory the last file was opened from).

import tkinter as tk
from tkinter import filedialog
import os

TEST_FILENAME = "test.txt"

if os.path.exists(TEST_FILENAME):
    os.remove(TEST_FILENAME)

root = tk.Tk()
root.withdraw()
filedialog.askopenfilename()

with open(TEST_FILENAME, "a") as f:
    f.write("Hello World")
my1e5 commented 1 year ago

Using os.getcwd() you can see the directory changing depending on where you open/save a file

import xdialog, os

print(os.getcwd())

TEST_FILENAME = "test.txt"

if os.path.exists(TEST_FILENAME):
    os.remove(TEST_FILENAME)

xdialog.open_file()
print(os.getcwd())
xdialog.open_file()
print(os.getcwd())

with open(TEST_FILENAME, "a") as f:
    f.write("Hello World")
[Running] python -u "c:\xdialog_testing\test.py"
c:\xdialog_testing
C:\test
C:\xdialog_testing

For example I start in c:\xdialog_testing, then open a file saved in C:\test and it changes the CWD. Then if I open a file in C\xdialog_testing it changes back.

my1e5 commented 1 year ago

Figured it out - there is an OFN flag that needs setting - https://learn.microsoft.com/en-us/windows/win32/api/commdlg/ns-commdlg-openfilenamea

image

using Flags=0x00081808 + (0x200 if multiple else 0) stops the current working directory from permanently changing

mathgeniuszach commented 1 year ago

Thanks for reporting! I'll take care of this now.

mathgeniuszach commented 1 year ago

Fixed by https://github.com/xMGZx/xdialog/commit/d7d09395301979fd1624d077d834bb3f83ea2c0a

If you have any more issues, let me know.