某些Python函数的.NET等价物

2 投票
4 回答
2838 浏览
提问于 2025-04-16 01:34

我正在尝试把一些Python代码移植到.NET上,想知道在.NET中有没有和以下Python函数相对应的功能,或者有没有一些代码片段能实现相同的功能。

os.path.split()
os.path.basename()

编辑

在Python中,os.path.basename()这个函数返回的是os.path.split的最后部分,而不是System.IO.Path.GetPathRoot(path)的结果。

我认为下面这个方法可以创建一个合适的os.path.split函数的移植版本,任何改进建议都很欢迎。我尽量按照http://docs.python.org/library/os.path.html上对os.path.split的描述来写的。

    public static string[] PathSplit(string path)
    {
        string head = string.Empty;
        string tail = string.Empty;

        if (!string.IsNullOrEmpty(path))
        {
            head = Path.GetDirectoryName(path);
            tail = path.Replace(head + "\\", "");
        }

        return new[] { head, tail };
    }

我不太确定我返回头部和尾部的方式,因为我其实不想通过参数把头部和尾部传递给这个方法。

4 个回答

0

为什么不直接使用IronPython,这样就能同时享受到两种语言的优点呢?

7

你需要找的是 System.IO.Path 类。

这个类有很多功能,可以帮你实现你想要的效果。

  • Path.GetDirectoryName(string):这个方法可以用来获取文件的目录名。
  • 如果你想要分割路径,可能需要用 String.Split(...) 来处理实际的路径名。你可以通过 Path.PathSeparator 来获取操作系统相关的分隔符。
  • 如果我理解错了关于 os.path.split 的意思,而你想要获取文件名,可以使用 Path.GetFileName(string)

请注意:你可以通过在 Visual Studio 中使用 对象浏览器 (Ctrl+Alt+J) 来查看 System.IO 命名空间下的所有成员。在这里,你可以找到 mscorlib -> System.IO,所有的类都会在那儿显示。

这就像是超级智能提示 :)

1

os.path.basename()

另一种选择是 System.IO.Path.GetPathRoot(path);

System.IO.Path.GetPathRoot("C:\\Foo\\Bar.xml") // Equals C:\\

编辑: 上面的代码返回的是路径的第一个部分,而 basename 应该返回路径的最后一部分。下面的代码示例展示了如何实现这一点。

os.path.split()

不幸的是,这个功能没有直接的替代品,因为在 .Net 中没有类似的功能。最接近的选择是 System.IO.Path.GetDirectoryName(path),但是如果你的路径是 C:\Foo,那么 GetDirectoryName 会返回 C:\Foo,而不是 C:Foo。这个方法只适用于获取实际文件路径的目录名称。

所以你需要写一些像下面这样的代码来拆分这些路径:

public void EquivalentSplit(string path, out string head, out string tail)
{

    // Get the directory separation character (i.e. '\').
    string separator = System.IO.Path.DirectorySeparatorChar.ToString();

    // Trim any separators at the end of the path
    string lastCharacter = path.Substring(path.Length - 1);
    if (separator == lastCharacter)
    {
        path = path.Substring(0, path.Length - 1);
    }

    int lastSeparatorIndex = path.LastIndexOf(separator);

    head = path.Substring(0, lastSeparatorIndex);
    tail = path.Substring(lastSeparatorIndex + separator.Length,
        path.Length - lastSeparatorIndex - separator.Length);

}

撰写回答