Search code examples
pythonfilepathkivycopy

The Python open() function does not create a new file or crash when in write mode


I'm working on a Kivy application that lets you edit images. To do this, the user selects his image via the file browser (filechooser from plyer) and once the file has been selected, the path to the image is supposed to be displayed and the file copied. The path to the file is displayed in the application, but my problem is that copying the file doesn't work. When I copy the file into the directory provided, Python crashes and tells me that the directory doesn't exist, and when I copy the file elsewhere to test it, Python doesn't crash but doesn't copy anything, as if it wasn't reading the lines of code.

code (image_editing.py):

class LayoutSelectImagePath(BoxLayout):
    path_to_image = StringProperty("")
    def select_image(self):
        # the file chooser return a list on selected files
        path_image = filechooser.open_file(title="choose an image",
                                     filters=[("Image", "*.jpg", "*.png", "*.ico", "*.bmp")])
        if len(path_image) > 0:
            self.path_to_image = path_image[0]  # show the path in the UI (OK)
            self.copy_image()


    def copy_image(self):
        file_base = open(self.path_to_image, "rb") #read the image file
        image_base = file_base.read()
        file_base.close()

        image_name = path.basename(self.path_to_image) # get the name of the image file
        file_to_work = open(f"image_work_dir/{image_name}", "wb") # write the image in a new image file in a new dir (NOT OK)
        file_to_work.write(image_base)
        file_to_work.close()

I've tried other ways of copying the file with shutil, os.system() but each time the copy doesn't work.Je précise que j'ai les droits d'écritures sur tous ce qui se trouve dans le répertoire du projet.

error code (only when I want to copy to the image_work_dir directory):

File "C:\Users\Trist\PycharmProjects\dev_image_edit\image_editing.py", line 28, in copy_image file_to_work = open(f"image_work_dir/{image_name}", "wb") # write the image in a new image file in a new dir (NOT OK) FileNotFoundError: [Errno 2] No such file or directory: 'image_work_dir/test.jpg'

i try to copy a file and/or to write a file but nothing work

project dir: enter image description here


Solution

  • I found the bug, plyer's filechooser changes the program's working directory, which means that files and folders that are in the program's real working directory are no longer found. To fix the problem I retrieve the current working directory with os.getcwd() then after using the file chooser I reset the working directory to its default value with os.chdir() and the value I retrieved earlier.

    code:

    app_work_dir = getcwd()
    path_image = filechooser.open_file(title="choose an image",
                          filters=[("Image", "*.jpg", "*.png",   "*.ico", "*.bmp")])
    chdir(app_work_dir)