如何通过Python在一个字符串中打开一堆.txt文件

2024-04-26 05:53:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我很清楚如何打开一个文件,使用open()函数非常简单,如下所示:

with open('number.txt', 'rb') as myfile:
    data=myfile.read()

但是,如果我想打开5.txt文件并在Python中将它们作为字符串查看,我的操作是什么呢?我应该使用os.listdir()的可能性吗?你知道吗


Tags: 文件函数字符串txtnumberreaddataos
2条回答

这里提供了一种灵活的/可重用的方法,可以完全满足您的需要:

def read_files(files):
    for filename in files:
        with open(filename, 'rb') as file:
            yield file.read()

def read_files_as_string(files, separator='\n'):
    files_content = list(read_files(files=files))
    return separator.join(files_content)

# build your files list as you need
files = ['f1.txt', 'f2.txt', 'f3.txt']
files_content_str = read_files_as_string(files)
print(files_content_str)

看来你需要。你知道吗

import os
path = "your_path"
for filename in os.listdir(path):
    if filename.endswith(".txt"):
        with open(os.path.join(path, filename), 'rb') as myfile:
            data=myfile.read()

相关问题 更多 >