python - 创建文件 python

标签 python user-interface directory tuples

我在用 python 创建文件时遇到了一些问题。我想在桌面上创建它并为其命名。我的程序应该在其中创建另一个文件夹并从用户那里获取名称,但是当我执行以下操作时:

def folder(self):
    home = os.sep.join((os.path.expanduser('~'),'Pulpit'))
    if not os.path.exists(home):
        home = os.path.join((os.path.expanduser('~'), 'Desktop'))
    opto = home + '\OptoMaQ'
    self.directory = opto
    nam = str(self.nmget.get())
    mypath = opto + '\%s'  %nam
    if not os.path.exists(opto):
        os.makedirs(opto)
        if len(nam) == 0:
            self.fold.config(text = 'This name is incorrect',background = 'red')
        else:   
            if not os.path.exists(mypath):
                os.makedirs(mypath)
                self.fold.config(text = 'Folder was created',background = 'green')
            else:
                self.fold.config(text = 'This name is taken',background = 'red')
    else:
        if len(nam) == 0:
            self.fold.config(text = 'This name is incorrect',background = 'red')
        else:   
            if not os.path.exists(mypath):
                os.makedirs(mypath)
                self.fold.config(text = 'Folder was created',background = 'green')
            else:
                self.fold.config(text = 'This name is taken',background = 'red')

当然是用于 GUI 编程。当我运行它时,出现错误:“opto = home + '\OptoMaQ' TypeError:只能将元组(不是“str”)连接到元组”。有趣的是,几天前它对我有用,但现在我不起作用了。有人可以帮助我吗?

最佳答案

用途:

if not os.path.exists(home):
    home = os.path.join(os.path.expanduser('~'), 'Desktop')
opto = home + r'\OptoMaQ'

os.path.join 不将元组作为参数,os.sep.join 则这样做。

关于python - 创建文件 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22987702/

相关文章:

python - Pandas Efficient Count 列中的唯一值然后找到该计数的最大值

c++ - QObject 多重继承

regex - Mercurial/.hgignore - 如何忽略除文件夹内容之外的所有内容?

python - 从 Panda Dataframe 获取 X Y 值

python - 我的 Python 代码还有改进的空间吗?

python - django-pipeline 不编译 sass 文件

java - 切换垂直 JScrollBar 最小/最大位置

c - 使用 GUI 制作程序

php Composer windows安装奇怪的目录错误

python - 没有参数的 Pytest 有错误的工作目录