I have multiple txt files with similar names as follow: item1.txt, item2.txt, item3.txt,
item700.txt what is the best way to read these files' data in using python? Thank you in advance
Use range()
function to iterate over the 700 integers:
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:
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())
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.