【问题标题】:Making directory using read txt file使用读取的txt文件制作目录
【发布时间】:2021-06-08 09:00:54
【问题描述】:

我正在尝试使用读取文件创建目录,但没有成功。

x= open(r'C:\Users\Fast Computer\Desktop\k.txt', 'r')
for f in x:
    path=r'C:\Users\Fast Computer\Desktop'
    n=f.readline()
    path=os.path.join(path,n)
    os.mkdir(path)

【问题讨论】:

    标签: python for-loop directory readfile txt


    【解决方案1】:

    我不知道你的文件包含什么,但是..

    在你的例子中..

    第 2 行已经在读取文件中的行。

    第 4 行将失败,因为您正在尝试从字符串运行 readline() 命令。

    从你的文件中读取的行也包含换行符,所以你应该去掉它们。

    例子:

    x= open(r'C:\Users\Fast Computer\Desktop\k.txt', 'r')
    for f in x:
        path=r'C:\Users\Fast Computer\Desktop'
        n=f.strip()
        path=os.path.join(path,n)
        os.mkdir(path)
    

    【讨论】:

      【解决方案2】:

      你能提供你的文本文件的内容吗? 如果路径需要递归创建目录,os.mkdir() 将失败。 改用os.makedirs()

      【讨论】:

        猜你喜欢
        • 2011-09-26
        • 2016-01-08
        • 1970-01-01
        • 2015-07-03
        • 1970-01-01
        • 2021-11-06
        • 2014-11-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多