[英]How do I retrieve the contents of all the files in a directory in a list each one?
I would like to read the all the files in a directory so I'm doing the following: 我想读取目录中的所有文件,因此需要执行以下操作:
path = '/thepath/of/the/files/*'
files = glob.glob(path)
for file in files:
print file
The problem is that when I print the files I don't obtain anything; 问题是,当我打印文件时,我什么也没得到。 any idea of how to return all the content of the files in a list per file?
关于如何返回每个文件列表中文件的所有内容的任何想法?
EDIT: I appended the path with an asterisk, this should give you all the files and directories in that path. 编辑:我在路径后附加了一个星号,这应该为您提供该路径中的所有文件和目录。
I would do something like the following to only get files. 我将执行以下操作,仅获取文件。
import os
import glob
path = '/thepath/of/the/files/*'
files=glob.glob(path)
for file in files:
if os.path.isfile(file):
print file
Your question is kind of unclear, but as I understand it, you'd like to get the contents of all the files in the directory. 您的问题尚不清楚,但据我了解,您想获取目录中所有文件的内容。 Try this:
尝试这个:
# ...
contents = {}
for file in files:
with open(file) as f:
contents[file] = f.readlines()
print contents
This creates a dict where the key is the file name, and the value is the contents of the file. 这将创建一个dict,其中键是文件名,而值是文件的内容。
Like in the comment I posted some time ago, this should work: 就像我前段时间发表的评论一样,这应该起作用:
contents=[open(ii).read() for ii in glob.glob(path)]
or this, if you want a dictionary instead: 或者,如果您想要字典,则:
contents={ii : open(ii).read() for ii in glob.glob(path)}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.