简体   繁体   English

在python3中打开多个txt文件

[英]Open multiple txt files in python3

I have multiple txt files with similar names as follow: item1.txt, item2.txt, item3.txt,我有多个名称相似的txt文件,如下所示:item1.txt、item2.txt、item3.txt、

item700.txt what is the best way to read these files' data in using python? item700.txt 使用 python 读取这些文件数据的最佳方法是什么? Thank you in advance提前谢谢你

Use range() function to iterate over the 700 integers:使用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()

A different way is to use glob.glob function to search for the text files:另一种方法是使用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

Note: Depending on your python version the Textfiles might not be sorted by os.listdir() prevent that by sorted(os.listdir())注意:根据您的 python 版本,文本文件可能不会按os.listdir()排序,防止按sorted(os.listdir())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM