首页 > 解决方案 > 如何从 txt 文档中获取文本并创建新目录?

问题描述

挑战是从文本文件中获取名称并在不同的目录中创建一个新文件夹。我的问题是,当我尝试这样做时,它提到

join() argument must be str, bytes, or os.PathLike object, not 'list'

有没有一种方法可以转换列表来做到这一点,或者有没有另一种我没有看到的方法?

import os

clientnames = "/home/michael/tafe/Customer Service Team/Customer Service Team new client names" #filepath/filename of new client names.

#Error handeling, if the txt file is missing then it will say the file is unavaliable.
if (os.path.isfile(clientnames)) == True:
    print("The file is avaliable, folder creation will now start.")
else:
    print("The file is unavaliable, please provide Customer Service Team new client names .txt file")

folderdir = "/home/michael/tafe/FS1/Administration/New_Customers" #filepath of where the new folders are to be created in.

#take name from txt file.
with open(clientnames, "r") as newfolder:
    for line in newfolder:
        newfolder = line.strip().split()
        created_folder = os.path.join(folderdir, newfolder)

os.mkdir(created_folder)
print("Directory '% s' created" % newfolder)

我对学习 python 还是很陌生,但是一旦我找到如何创建目录,我感觉我已经接近解决这个问题了。(挑战还有其他一些部分,但与此无关......)。

在 Visual Studio Code 上使用 Python 3.8.7 64 位。

标签: pythonpython-3.xtextdirectory

解决方案


问题在于以下for循环:

with open(clientnames, "r") as newfolder:
    for line in newfolder:
        newfolder = line.strip().split()
        created_folder = os.path.join(folderdir, newfolder)

star.split()返回一个类型的对象list。知道这newFolder将是一个list

created_folder = os.path.join(folderdir, newfolder)

就好像

created_folder = os.path.join("/home/michael/tafe/FS1/Administration/New_Customers", ["Tom", "Lam"])

python如何将字符串与列表连接起来?

删除.split(),看看会发生什么。


推荐阅读