读取目录中的多个文件作为 python 列表

reading multiple files in a directory as python list

我正在尝试将目录中的多个文件读取为 python 列表。 txt 文件包含 ID 列表。 例如,H104.txt

CZ104
Cz509
T3G63

分享我写的脚本,

files = ["H104.txt","H905.txt","H920B1.txt","T636.txt"]
# shell script for getting file list
#  ls | tr ' ' ',' | tr '\n' ',' | sed -r 's/[^,]+/"&"/g'


f = ["H104","H905","H920B1","T636"]
i = 0

while i < len(f):
    for filename in files:
        with open(filename, 'r') as onefile:
            f[i] = onefile.readlines()
    i += 1

print(H104)

我想使用它们各自的文件名作为变量来读取这些多个文件。上面的脚本给我 Nameerror NameError: name 'H104' is not defined.

我想要的输出, ["CZ104","Cz509","T3G63"]

I want to read these multiple files using their respective file names as a variable.

有点难说,但我想你需要这里的字典。例如:

# Fill the dict: keys are filenames, values are lists of lines.
file_lines = {}
for filename in files:
    with open(filename, 'rt') as file:
        lines = [line.rstrip('\n') for line in file.readlines()]
        file_lines[filename] = lines

# Access each file by its key in the dict.
print(file_lines['H104.txt'])

如果您不介意每行以 \n 换行符结尾,您还可以将阅读简化为 lines = file.readlines().