Python如何获取指定文件夹路径和文件内容

1、Python获取所选中的文件夹,并将其路径显示在lineedit中

  def openfile(self):              #获取文件所在的文件夹
        # filename,fileType = QFileDialog.getOpenFileName(self,"打开文件",'./',"Image Files(*.jpg *.png *.txt *.py)")
        self.fileDir = QFileDialog.getExistingDirectory(self,"打开文件","./")    #得到指定文件夹的路径
        self.fileDir = self.fileDir + "/"
        if len(self.fileDir) != 0:          #说明已经选中了文件夹
            lineedit = "文件所在文件夹路径为:" +self.fileDir
            self.lineEdit_2.setText(lineedit)
            self.filelist = os.listdir(self.fileDir)
        else:
            print("文件夹不存在")
            # with open(self.fileName,'r',encoding='utf-8') as f:
            #     for line in f.readlines():
            #         text += line
            # self.textedit.setPlainText(text)

2、Python打开文件并获取指定文件夹下的文件内容

    def openfile(self):
        filename,fileType = QFileDialog.getOpenFileName(self,"打开文件",'./',"Image Files(*.jpg *.png *.txt *.py)")
        if len(fileType) != 0:
            self.fileName = filename
            text = ''
            with open(self.fileName,'r',encoding='utf-8') as f:
                for line in f.readlines():
                    text += line
            self.textedit.setPlainText(text)  #将读取到的文件显示在textedit中

你可能感兴趣的:(Python,PyQt,python,pyqt)