[英]How to load .txt files in python for loop?
我有 10 个 txt 格式的数据:a1.txt,a2.txt,...,a10.txt 我想在 for 循环中一个一个地加载它们。
加载我使用的文件
data = read_data('a1.txt');
但我不确定如何在 for 循环中使用它。
在以 .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')]
pathlib (python 3.4+)的另一种方法。 它还识别用于匹配的 a:
from pathlib import Path
files = [str(f) for f in Path(mypath).iterdir() if f.match("a*.txt")]
使用range()
function 生成数字序列,然后使用字符串格式化组合文件名:
for number in range(1, 11):
filename = 'a%d.txt' % number
data = read_data(filename)
如果文件夹中有 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.