簡體   English   中英

在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()

假設所有且只有文本文件都在文件夾中

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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM