简体   繁体   English

如何从 txt 文档中获取文本并创建新目录?

[英]How to take text from a txt document and create a new directory?

The challenge is to take a name from a text file and create a new folder in a different directory.挑战是从文本文件中获取名称并在不同的目录中创建一个新文件夹。 My issue is that when I attempt to do so it mentions that the我的问题是,当我尝试这样做时,它提到

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

Is there a way of converting a list to do this or is there another way of doing this I'm not seeing?有没有一种方法可以转换列表来做到这一点,或者有没有另一种我没有看到的方法?

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)

I am pretty new to learning python but feel like I'm close to figuring this out once I find how to get the directory created.我对学习 python 还是很陌生,但是一旦我找到了如何创建目录,我就快要搞清楚了。 (there are some other parts to the challenge as well but are not related to this...). (挑战还有其他一些部分,但与此无关......)。

Using Python 3.8.7 64-bit on Visual Studio Code.在 Visual Studio Code 上使用 Python 3.8.7 64 位。

The problem lies in the for loop of:问题在于for循环:

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

star.split() returns an object of type list . star.split()返回list类型的 object 。 Knowing that newFolder will be a list ,知道newFolder将是一个list

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

Is like就好像

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

How would python join the string with the list? python 如何将字符串与列表连接?

Remove the .split() and see what happens.删除.split()看看会发生什么。

os.path.join accepts only strings, and you are passing a list as a second argument. os.path.join仅接受字符串,并且您将列表作为第二个参数传递。 Eg lets assume your newfolder looks like this: ['folder1', 'folder2', 'etc'] , your call to this function looks like:例如,假设您的新文件夹如下所示: ['folder1', 'folder2', 'etc'] ,您对这个newfolder的调用如下所示:

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

Instead you have to pass only strings, like:相反,您必须只传递字符串,例如:

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

To do this, you can use splat operator, to unpack argument lists:为此,您可以使用splat运算符来解压缩参数列表:

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

Update the other problem as pointed by @Ann Zen is the for loop.更新@Ann Zen 指出的另一个问题是 for 循环。 Each iteration changes created_folder variable, which is used only after loop.每次迭代都会更改created_folder变量,该变量仅在循环后使用。 You need to read all text from file (as list), then after loop join it into path using *newfolder .您需要从文件中读取所有文本(作为列表),然后在循环后使用*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)

Update 2 Another problem is when you are trying to create multiple nested folders in a path, eg create folder test1 in folder test2, but folder test2 doesn't exist yet, so need to be created first.更新 2另一个问题是当您尝试在路径中创建多个嵌套文件夹时,例如在文件夹 test2 中创建文件夹 test1,但文件夹 test2 尚不存在,因此需要先创建。 Assuming each folder is named in another line in file clientnames :假设每个文件夹在文件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)

Then if the file clientnames looks like this:然后,如果文件clientnames如下所示:

test1
test2
test3

it will first create folderdir/test1 , then folderdir/test1/test2 , and at the end folderdir/test1/test2/test3 , so not to throw FileNotFoundError它将首先创建folderdir/test1 ,然后folderdir/test1/test2 ,最后folderdir/test1/test2/test3 ,所以不要抛出FileNotFoundError

Update 3 If you want to create folder for each line of text from clientnames , all rooted in folderdir simply don't stack the path, and create new one for each line.更新 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从tkinter获取条目并将其打印在txt文档中? - How can I take an entry from tkinter and print it in a txt document? 如何从txt文件中提取一列并保存在新矩阵中 - How to take a column from a txt file and save in a new matrix 如何将项目放在列表中,并在单独的行上将它们打印到新的.txt文档中 - How to take items in a list, and print them to a new .txt document on separate lines 使用命令中的额外文本创建一个新的 .txt 文件作为输出 - Create a new .txt file as output with extra text from commands 我倾向于通过读取另一个文件来创建一个新文件,但是当我尝试使用这个文件时,系统返回:没有这样的文件或目录:'new_text_file.txt' - I tend to create a new file by reading from another one, but when I try use this file, the sys returns:No such file or directory: 'new_text_file.txt' 如何使用cmd从头开始创建新的文本文档并将其另存为.py文件? - How to create a new text document from scratch and save it as .py file using cmd? 如何从 .t​​xt 列表中获取数字并将结果保存在另一个 .txt 中? - How to take numbers from a .txt list and save the result in another .txt? 如何在目录的特定路径中创建文件 .txt - How to create file .txt in a specific path of a directory 在python目录中为每个.pdf文件创建一个新的.txt文件 - Create a new .txt file for each .pdf files in a directory in python 在目录 PYTHON SCRIPT 中创建新的 txt 文件 - Create new txt file inside directory PYTHON SCRIPT
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM