python - 在 Python 中从字符串创建路径和文件名

标签 python

给定以下字符串:

dir/dir2/dir3/dir3/file.txt
dir/dir2/dir3/file.txt
example/directory/path/file.txt

我希望在这些目录中创建正确的目录和空白文件。

我导入了 os 模块,我看到有一个 mkdir 函数,但我不确定如何创建整个路径和空白文件。任何帮助,将不胜感激。谢谢。

最佳答案

这里是您所有问题的答案(目录创建和空白文件创建)

import os

fileList = ["dir/dir2/dir3/dir3/file.txt",
    "dir/dir2/dir3/file.txt",
    "example/directory/path/file.txt"]

for file in fileList:
    dir = os.path.dirname(file)
    # create directory if it does not exist
    if not os.path.exists(dir):
        os.makedirs(dir)
    # Create blank file if it does not exist
    with open(file, "w"):
        pass

关于python - 在 Python 中从字符串创建路径和文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8344315/

相关文章:

减少基类中小子类数量的 Pythonic 方法?

python - 在 Windows 记事本的 Python 中创建 UTF-16 换行符

python - 将最后一个值替换为之前的值

python - 如何在 python 中使用 MySQLdb 模块覆盖聚合查询中的 NULL 值?

Python 简单 TCP 中继

Python 的数学计算很奇怪,为什么会这样?

python - 选择两个给定日期之间的 pandas 数据框,其中两列的值相等

python - Scikit-learn:覆盖分类器中的类方法

python - 在 Pandas DataFrame 中的所有行上运行基于 numpy 的函数的快速替代方法

python - xlrd 中的 col 输出似乎是 xf 格式文本。我该如何摆脱这个?