正如Inbar Rose已经解释过的,您可以使用glob获得文件列表。要将输入文件名转换为适当的输出文件名,可以使用正则表达式从输入名称中提取文件号,然后使用它构造输出名称。在
像这样:import os
import glob
import re
inputPath = '.' # the directory where your files are stored
num = 5 # the fixed parameter, n
# first obtain all the data*.txt files in the directory
for inputName in glob.glob(os.path.join(inputPath,'data*.txt')):
# attempt to extract the file number from the input name
fileNum = re.findall(r'data([0-9]+)\.txt',inputName)
# if not successful, skip this file
if not fileNum: continue
# create the output filename using the fle number and the fixed parameter
outputName = 'output_data{0}_{1}.txt'.format(fileNum[0],num)
# add the input path to the filename, or use a different path if necessary
outputName = os.path.join(inputPath,outputName)
# process the file
x,y = genfromtxt(inputName).T
with open(outputName,'wb') as file:
# do the rest of your code here
pass