[英]Loading files from directory from user
I'm trying to load a lot of files from a directory. 我正在尝试从目录中加载很多文件。 I used to be able to do it by having this
我曾经可以通过这样做
#directory where all data will be stored
dataDir="C:/Users/me/Desktop/Data/"
Files=[] #list of files
for file in os.listdir(dataDir):
Files.append(scipy.io.loadmat(dataDir+file))
But now, I'm trying to have the user select the folder so I have this: 但是现在,我正在尝试让用户选择文件夹,所以我需要这样做:
import tkinter
from tkinter import filedialog
from tkinter import *
root=tkinter.Tk()
filename=filedialog.askdirectory(parent=root,title='Choose a file')
print (filename)
#directory where all data will be stored
dataDir=('%s',filename)
Files=[] #list of files
for file in os.listdir(dataDir):
Files.append(scipy.io.loadmat(dataDir+file))
and it is giving me this error: "for file in os.listdir(dataDir): TypeError: listdir: path should be string, bytes, os.PathLike or None, not tuple) 它给了我这个错误:“对于os.listdir(dataDir)中的文件:TypeError:listdir:路径应为字符串,字节,os.PathLike或None,而不是元组)
I tried making filename into a string by doing str(filename), and it still wouldn't work. 我尝试通过执行str(filename)将filename制成字符串,但仍然无法正常工作。 Any ideas?
有任何想法吗?
When you define dataDir = ('%s', filename)
you are creating a tuple with two elements. 当定义
dataDir = ('%s', filename)
您将创建一个包含两个元素的元组。 One is '%s'
and the other the value of filename
. 一个是
'%s'
,另一个是filename
的值。
If I understand correctly you shoud use dataDir = '%s' % filename
. 如果我理解正确,则应该使用
dataDir = '%s' % filename
。 That way dataDir
will be a string with the value of filename
. 这样,
dataDir
将是一个具有filename
值的字符串。
You create tuple in command 您在命令中创建元组
dataDir=('%s',filename)
and you use it in listdir(dataDir)
which expect string 然后在
listdir(dataDir)
字符串的listdir(dataDir)
使用它
Use filename
directly in listdir
直接在
listdir
使用filename
for file in os.listdir(filename):
The error states that the path you give listdir
should be a str
and that you gave it a tuple
. 该错误指出,您给
listdir
的路径应该是str
,并且给了它一个tuple
。
With dataDir=('%s',filename)
, dataDir
is a tuple containing two strings. 如果
dataDir=('%s',filename)
,则dataDir
是一个包含两个字符串的元组。 However, filename is already a str
. 但是,filename已经是一个
str
。 Instead of os.listdir(dataDir)
, try os.listdir(filename)
. 尝试使用
os.listdir(filename)
代替os.listdir(dataDir)
os.listdir(filename)
。
You will need to import os
. 您将需要
import os
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.