gpt4 book ai didi

python - 读取所有目录下的所有文件

转载 作者:太空狗 更新时间:2023-10-29 19:37:45 27 4
gpt4 key购买 nike

<分区>

我的代码可以读取单个文本文件的值,但在读取所有目录中的所有文件并将所有内容放在一起时遇到困难。

这是我的:

filename = '*'
filesuffix = '*'
location = os.path.join('Test', filename + "." + filesuffix)
Document = filename
thedictionary = {}
with open(location) as f:
file_contents = f.read().lower().split(' ') # split line on spaces to make a list
for position, item in enumerate(file_contents):
if item in thedictionary:
thedictionary[item].append(position)
else:
thedictionary[item] = [position]
wordlist = (thedictionary, Document)
#print wordlist
#print thedictionary

请注意,我试图将通配符 * 插入文件名以及文件后缀的通配符中。我收到以下错误:

“IOError:[Errno 2] 没有这样的文件或目录:'Test/.'”

我不确定这是否是正确的方法,但似乎如果我以某种方式让通配符起作用 - 它应该起作用。

我已经让这个例子起作用了:Python - reading files from directory file not found in subdirectory (which is there)

有点不同 - 但不知道如何更新它以读取所有文件。我认为在这组初始代码中:

previous_dir = os.getcwd()
os.chdir('testfilefolder')
#add something here?
for filename in os.listdir('.'):

我需要在有外部 for 循环的地方添加一些东西,但不太知道要放入什么......

有什么想法吗?

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com