将每个文件的内容读取到 Python 中的单独列表中
Read the contents of each file into a separate list in Python
我想在Python中准备好每个文件的内容到一个单独的列表中。我习惯于用 bash for 循环做一些类似的事情,我可以说:
for i in file_path; do writing stuff; done
使用 glob 我可以加载每个文件,但我想将每个文件的内容保存在一个列表中,以便稍后将它们用于比较目的,而无需对列表的名称和数量进行硬编码。这是我在 python:
中取得的进展
import sys
import glob
import errno
list_$name[] ##<this is not python
path = './dir_name/*'
files = glob.glob(path)
for name in files:
try:
with open(name) as f:
lines = f.read().splitlines()
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
我想做的事情是可能的还是我必须使用 shell 脚本来循环处理每个文件?
import sys
import glob
import errno
list_$name[] ##<this is not python
path = './dir_name/*'
files = glob.glob(path)
contents = []
for name in files:
try:
with open(name) as f:
lines = f.read().splitlines()
contents.append (lines)
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
# Your contents list will now be a list of lists, each list containing the contents of one file.
我想在Python中准备好每个文件的内容到一个单独的列表中。我习惯于用 bash for 循环做一些类似的事情,我可以说:
for i in file_path; do writing stuff; done
使用 glob 我可以加载每个文件,但我想将每个文件的内容保存在一个列表中,以便稍后将它们用于比较目的,而无需对列表的名称和数量进行硬编码。这是我在 python:
中取得的进展import sys
import glob
import errno
list_$name[] ##<this is not python
path = './dir_name/*'
files = glob.glob(path)
for name in files:
try:
with open(name) as f:
lines = f.read().splitlines()
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
我想做的事情是可能的还是我必须使用 shell 脚本来循环处理每个文件?
import sys
import glob
import errno
list_$name[] ##<this is not python
path = './dir_name/*'
files = glob.glob(path)
contents = []
for name in files:
try:
with open(name) as f:
lines = f.read().splitlines()
contents.append (lines)
except IOError as exc:
if exc.errno != errno.EISDIR:
raise
# Your contents list will now be a list of lists, each list containing the contents of one file.