在 python3 中打开多个 txt 文件

Open multiple txt files in python3

我有多个类似名称的 txt 文件,如下所示: item1.txt, item2.txt, item3.txt,

item700.txt 使用 python 读取这些文件数据的最佳方式是什么?提前谢谢你

使用range()函数迭代700个整数:

import os
import io

work_dir = "path/to/workdir"

for index in range(1, 701):
    name = "item{index}.txt".format(index=index)
    path = os.path.join(work_dir, name)
    with io.open(path, mode="r", encoding="utf-8") as fd:
        content = fd.read()

另一种方法是使用 glob.glob 函数搜索文本文件:

for path in glob.glob(os.path.join(work_dir, "item*.txt")):
    with io.open(path, mode="r", encoding="utf-8") as fd:
        content = fd.read()

Assuming all and only the text-files are in a Folder

import os 

all_txt_files = os.listdir(file_dir)

for txt in all_txt_files:
    txt_dir = file_dir + txt    
    with open(txt_dir, 'r') as txt_file:

    # read from a single Textfile whatever you want to

注意: 根据您的 python 版本,文本文件可能不会按 os.listdir() 排序防止按 sorted(os.listdir())