【问题标题】:How to read a directory whose name has characters like " / " in python?如何在python中读取名称中包含“/”等字符的目录?
【发布时间】:2012-12-26 21:04:12
【问题描述】:

我正在开发 OSX 10.5.8,它甚至允许文件名字符上出现“/”。

我有一个 wx.TextCtrl 包含一个要读取的目录(音乐艺术家的目录),有这样的乐队叫

  • //紧张//
  • ///▲▲▲\\

所以在文本字段中我写下一个目录名称,这样写

/Users/....../Music/iTunes/iTunes Music////▲▲▲\\\/Untitled/

当然我读的时候会报错,因为程序无法识别带和斜线的名称,我该如何解决呢?

【问题讨论】:

  • 你能给我们输出os.listdir() 的父目录,里面有这样的子目录吗?它会向我们展示使用了什么代码点。
  • 也许ls -b 有助于找出它是什么字符。
  • 见Mac OS X Lion: What are invalid characters for a file name?;在终端的文件名中使用: 可以在Finder 和iTunes 中显示为/,反之亦然。将/ 替换为:,你就在那里。
  • 这是输出 => Traceback(最近一次调用最后):文件“/Users/.../Documents/python/MusicOrganizer/libs/music.py”,第 105 行,在 handlerAnalyze aListSongs = self.hFileSystemOp.readDirectorySongs(self.sMusicSource) File "/Users/..../Documents/python/MusicOrganizer/libs/files.py", line 80, in readDirectorySongs aListFiles = os.listdir(sDirectory) OSError: [ Errno 2] 没有这样的文件或目录:'/Users/.../Music/iTunes/iTunes Music////\xe2\x96\xb2\xe2\x96\xb2\xe2\x96\xb2\\\\\ \/无标题/'
  • @axel:这不是我要求的;我想要列出 iTunes Music 目录。 :-)

标签: macos python-2.7 wxpython special-characters


【解决方案1】:

尝试将文件名(不是目录名)中的/ 字符替换为:。

【讨论】:

  • 在 Finder 和文件对话框中,那些 : 字符显示为斜线,真的很混乱:(
  • 在 OS X 10.7 和 10.8 上确认。
  • 我什至尝试使用更简单的名称/Users/......./Music/iTunes/iTunes Music/::Tense::/Memory/ 代表名为 //Tense// 的目录,但无事可做。但我有 osx 10.5.8
  • 如果可能的话,我想在我的文本字段上写下目录的真实名称。
【解决方案2】:

我会推荐使用 wxPython 的内置小部件,例如 wx.FileDialog 或 filebrowsebutton

这是一个允许您选择多个文件的简单示例:

def onOpenFile(self, event):
    """
    Create and show the Open FileDialog
    """
    dlg = wx.FileDialog(
        self, message="Choose a file",
        defaultDir=self.currentDirectory, 
        defaultFile="",
        wildcard=wildcard,
        style=wx.OPEN | wx.MULTIPLE | wx.CHANGE_DIR
        )
    if dlg.ShowModal() == wx.ID_OK:
        paths = dlg.GetPaths()
        print "You chose the following file(s):"
        for path in paths:
            print path
    dlg.Destroy()

我建议下载 wxPython 演示以查看它的这个小部件的示例以及我提到的另一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-28
    • 1970-01-01
    • 1970-01-01
    • 2019-01-16
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多