首页 > 解决方案 > 使用读取的txt文件制作目录

问题描述

我正在尝试使用读取文件创建目录,但它不起作用。

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)

标签: pythonfor-loopdirectoryreadfiletxt

解决方案


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

在你的例子中..

第 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)

推荐阅读