python - 将打开的文件从一个函数传递到另一个函数

标签 python function file file-handling

我是 Python 初学者,请多多包涵。我在 GUI 上编写了一些代码,允许用户使用一个按钮 (browse_inputfile) 选择文件,然后显示文件路径,然后用户可以单击另一个按钮对该文件运行转换 (run_conversion)。

然而,要做到这一点,我必须定义一个全局变量,使打开的文件能够从一个函数传递到另一个函数。有一个更好的方法吗?我尝试传递路径并在第二个函数中实际打开它,但这会产生“找不到文件”错误,我认为这是由于字符串路径中使用的“\”所致。

这是我的代码:

def browse_inputfile(self):
       global inputfile
       inputfile = open(QtGui.QFileDialog.getOpenFileName(self, "Open Data File", "", "txt files (*.txt)"),'r+')`

然后有一些代码使用“inputfile.name”来显示路径。

第二个函数是这样的:

def run_conversion(self):
   global inputfile     
   if inputfile: # if user didn't pick a file don't continue
      #do stuff
      inputfile.close()

我知道使用全局变量不是好的做法,那么我如何将打开的文件从一个函数传递到另一个函数并让用户在文件上运行“东西”之前单击第二个按钮?

我希望他们能够在对文件进行“操作”之前检查文件是否正确。

谢谢

最佳答案

使用 inputfile 作为类的字段,这样就不需要将文件作为参数传递或使用全局变量。

class MyClass:
    def browse_inputfile(self):
        self.inputfile = open(QtGui.QFileDialog.getOpenFileName(self, "Open Data File", "", "txt files (*.txt)"),'r+')`
        # you code for display the path


    def run_conversion(self):
        if self.inputfile: # if user didn't pick a file don't continue
            #do stuff
            self.inputfile.close()

关于python - 将打开的文件从一个函数传递到另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33955835/

相关文章:

php - 访问root以外文件的方法

python - pysnmp 示例程序中的 asyncio "Task was destroyed but it is pending!"

python - 类型错误 : 'class Meta' got invalid attribute(s): constraints

javascript - 将函数参数作为字符串在函数本身中使用时遇到问题

C - 凯撒密码 [将代码移至函数]

Java - 从文本文件中读取对象

c# - 在 C# 中将 Excel 工作表的内容写入控制台时,输出不是人类可读的格式

字符串中的 Python 最短唯一 ID

javascript - 从 javascript 在 Flask 服务器上调用 web 服务方法

javascript - 将 JavaScript 移植到 C#(存储在数组中的函数)