[英]How to load .txt files in python for loop?
I have 10 data in txt format: a1.txt,a2.txt,...,a10.txt and I want to load them one by one in a for loop.我有 10 个 txt 格式的数据:a1.txt,a2.txt,...,a10.txt 我想在 for 循环中一个一个地加载它们。
To load a file I use加载我使用的文件
data = read_data('a1.txt');
but I am not sure how to use it in a for loop.但我不确定如何在 for 循环中使用它。
Search for files inside path that end with.txt在以 .txt 结尾的路径内搜索文件
from os import listdir
from os.path import isfile, join
mypath='/tmp'
files = [f for f in listdir(mypath) if isfile(join(mypath, f)) and f.endswith('.txt')]
Another approach with pathlib (python 3.4+). pathlib (python 3.4+)的另一种方法。 It recognizes also the a for matching:它还识别用于匹配的 a:
from pathlib import Path
files = [str(f) for f in Path(mypath).iterdir() if f.match("a*.txt")]
Use the range()
function to generate a sequence of numbers, and then use string formatting to assemble the filename:使用range()
function 生成数字序列,然后使用字符串格式化组合文件名:
for number in range(1, 11):
filename = 'a%d.txt' % number
data = read_data(filename)
If you have the txt files in a folder you could read the entire folder and loop through the txt files in it.如果文件夹中有 txt 文件,则可以读取整个文件夹并循环浏览其中的 txt 文件。
import glob
folder_path = 'path/to/the/folder'
for filename in glob.glob(folder_path, '*.txt')):
#Your process for each file
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.