面临的挑战是从文本文件中获取名称,然后在其他目录中创建一个新文件夹。我的问题是,当我尝试这样做时,它提到
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位。
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禅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)
Update 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
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句