python读取目录下所有文件名_如何在python中只读取目录的文件名,然后对所有文件执行相同的操作?...

正如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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值