【问题标题】:How to take text from a txt document and create a new directory?如何从 txt 文档中获取文本并创建新目录?
【发布时间】:2021-01-08 13:53:52
【问题描述】:

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

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 位。

【问题讨论】:

  • 好吧,newfolder 是一个列表,所以不清楚您要达到的目标是什么,但不妨试试os.path.join(folderdir, *newfolder)。注意星号。

标签: python python-3.x text directory


【解决方案1】:

os.path.join 仅接受字符串,并且您将列表作为第二个参数传递。例如。假设您的 newfolder 如下所示:['folder1', 'folder2', 'etc'],您对该函数的调用如下所示:

>>> os.path.join(folderdir, ['folder1', 'folder2', 'etc'])
# error

相反,您必须只传递字符串,例如:

os.path.join(folderdir, 'folder1', 'folder2', 'etc')
# 'folderdir/folder1/folder2/etc'

为此,您可以使用 splat 运算符来解压缩参数列表:

os.path.join(folderdir, *newfolder)
# 'folderdir/folder1/folder2/etc'

更新 @Ann Zen 指出的另一个问题是 for 循环。每次迭代都会更改created_folder 变量,该变量仅在循环后使用。您需要从文件中读取所有文本(作为列表),然后在循环后使用*newfolder 将其加入路径。

with open(clientnames, "r") as newfolder:
    newfolder = newfolder.read()
    newfolder = [t for t in newfolder.split(' ') if len(t)>0]
created_folder = os.path.join(folderdir, *newfolder)

更新 2 另一个问题是当您尝试在路径中创建多个嵌套文件夹时,例如在文件夹test2中创建文件夹test1,但是test2文件夹还不存在,所以需要先创建。 假设每个文件夹在文件 clientnames 的另一行中命名:

with open(clientnames, "r") as newfolder:
    folderpath = folderdir
    for line in newfolder.readlines():
        foldername = line.strip()
        folderpath = os.path.join(folderpath, foldername)
        os.mkdir(folderpath)

那么如果文件clientnames看起来像这样:

test1
test2
test3

它会先创建folderdir/test1,然后是folderdir/test1/test2,最后是folderdir/test1/test2/test3,所以不要抛出FileNotFoundError

更新 3 如果你想为clientnames 中的每一行文本创建文件夹,所有根植于folderdir 的都不要堆叠路径,并为每一行创建一个新文件夹。

with open(clientnames, "r") as newfolder:
    for line in newfolder.readlines():
        foldername = line.strip()
        folderpath = os.path.join(folderdir, foldername)
        os.mkdir(folderpath)

【讨论】:

  • 嘿,感谢您查看代码,我已经实现了您的代码和@Ann Zens 代码,虽然我能够创建一个新文件夹,但它只接受文本的第一个字符在 .txt 文件中。向 txt 文件添加超过 1 个字符会显示错误:发生异常:FileNotFoundError [Errno 2] 没有这样的文件或目录:'/home/michael/tafe/FS1/Administration/New_Customers/A/c/m/e/ _/C/o/r/p/e/r/a/t/i/o/n' 这是否与代码读取 txt 文件的方式有关,或者这只是 splat 运算符的工作方式?
  • @MadMike 它显示错误,因为您尝试创建 /home/michael/tafe/FS1/Administration/New_Customers/Acme_Corporation 而不是路径 /home/michael/tafe/FS1/Administration/New_Customers/A/c/m/e/_/C/o/r/p/e/r/a/t/i/o/n 并且要做到这一点,所有以前的文件夹都必须存在,例如。文件夹/home/michael/tafe/FS1/Administration/New_Customers/A/c/m/e/_/C/o/r/p/e/r/a/t/i/o(不存在)。所以问题在于读取文件。 Split(' ') 应该在每个空格上划分您的文本。你的文件clientnames 包含什么?
  • 所有客户端名称 .txt 文件都是“Acme Corporation”,没有其他文本、空格或撇号 ("")。如果你打开一个 txt 文档并输入 Acme Corporation,那就是文件中的全部内容。
  • 将 .split() 添加到 newfolder = line.strip().split() 显示以下错误:[Errno 2] No such file or directory: '/home/michael/tafe/FS1 /Administration/New_Customers/Acme/Corperation' 看起来 split 现在只是用空格分隔两个 txt
  • 只读一行,你可以使用newfolder.read().strip()。如果您要尝试创建多个嵌套文件夹,请查看我的答案的更新 2。
【解决方案2】:

问题出在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() 看看会发生什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 2018-04-13
    • 2013-06-16
    • 1970-01-01
    • 2014-08-13
    相关资源
    最近更新 更多