How to Open & Save Files in Python PyQt5

In this Python PyQt5 article we are going to learn How to Open & Save Files in Python PyQt5, so Python is powerful programming language that can be used to develop different types of applications including desktop applications. PyQt5 is popular Python GUI library that allows developers to create graphical user interfaces (GUIs) for desktop applications. In this article we are going to talk  how to open and save files in Python PyQt5.

 

 

So first let’s start from opening a file in Python PyQt5.

in the above code we have imported QFileDialog and QApplication classes from PyQt5.QtWidgets module. after that we have created an instance of the QApplication class.

After that we have used getOpenFileName method of the QFileDialog class to display the file dialog box.

 

 

Now let’s talk about saving a file in PyQt5, for saving a file in PyQt5, we also use the QFileDialog widget. however this time we use getSaveFileName method instead of the getOpenFileName method. this is an example of how to use the QFileDialog widget to save a file:

in the above code we have used getSaveFileName method of QFileDialog class to display save file dialog box. this method takes the same four arguments as getOpenFileName method.

If user selects a filename, we open the file using open function and write the string Welcome to GeeksCoders.com to it using the write method.

 

 

 

This is the complete code for this article

In this code we have created new class MainWindow that inherits from QMainWindow. after that we have created two buttons in the constructor of the class, one for opening a file and one for saving a file. we set the geometry of each button using the setGeometry method and connect their clicked signal to corresponding method, open_file for the Open File button, and save_file for the Save File button.

open_file method uses getOpenFileName method of the QFileDialog class to display file dialog box. this method takes self argument as parent widget which in this case is MainWindow object itself. if the user selects file, we open the file using the open function and read its contents using the read method. We then print the contents to the console.

save_file method uses the getSaveFileName method of the QFileDialog class to display save file dialog box. if user selects a filename, we open file using the open function and write the string Welcome to GeeksCoders.com to it using the write method.

 

 

 

Run your code and this is the result

How to Open & Save Files in Python PyQt5
How to Open & Save Files in Python PyQt5

 

 

Learn More on Python GUI

Leave a Comment