如何在python中读取目录的文件名,然后对所有目录执行相同的工作



我有一个python脚本,在最开始从输入数据文件中读取这一行:

    x,y = genfromtxt('data1.txt').T

然后我继续对x,y进行处理(它取决于一个固定的参数,例如n=5)。最后,我用以下行生成输出文件

    with open('output_data1_n{0}.txt'.format(num),'wb') as file: 

这给了我output_data1_n5.txt,并在其中写入xnew和ynew。

问题:我有一个目录,里面有很多txt文件!如何系统地为该目录下的所有文件执行此工作,而不是手动为每个输入文件执行此工作?

它应该是这样的:获取文本文件(例如os。)作为字符串并将其替换为input,然后生成包含参数n的输出名称。

谢谢你的建议。

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

试试glob模块

它允许你在一个目录中获得一个文件名列表,其中包含一些通配符。

的例子:

from glob import glob
from os import path
def get_files_in(folder, pattern='*.txt'):
    return glob(path.join(folder, pattern))

用法:

get_files_in('C:/temp') # files in C:/temp that are ending with .txt
get_files_in('C:/temp', '*.xml') # files in C:/temp that are ending with .xml
get_files_in('C:/temp', 'test_*.csv') # files in C:/temp that start with test_ and end in .csv