How to read all files in one folder and apply a function over them in python?

谁说我不能喝 提交于 2020-04-17 04:06:09

问题


I would like to run a function over all files in one folder and create new files out of them. I have put the code for one file bellow. I would appreciate it if you kindly help me.

def newfield2(infile,outfile):
    output = ["%s\t%s" %(item.strip(),2) for item in infile]
    outfile.write("\n".join(output))
    outfile.close()
    return outfile


infile = open("E:/SAGA/data/2006last/325125401.all","r")
outfile = open("E:/SAGA/data/2006last/325125401_edit.all","r")

I would like to change all the files in the 'E:/SAGA/data/2006last/' folder and create new files with edit extension.


回答1:


Use os.listdir() to list all files in a directory. The function returns just the filenames, not the full path. The os.path module gives you the tools to construct filenames as needed:

import os

folder = 'E:/SAGA/data/2006last'

for filename in os.listdir(folder):
    infilename = os.path.join(folder, filename)
    if not os.path.isfile(infilename): continue

    base, extension = os.path.splitext(filename)
    infile = open(infilename, 'r')
    outfile = open(os.path.join(folder, '{}_edit.{}'.format(base, extension)), 'w')
    newfield2(infile, outfile)



回答2:


import os

def apply_to_all_files:
    for sub_path in os.listdir(path):
        next_path = os.path.join(path, sub_path)
        if os.path.isfile(next_path):
            infile = open(next_path,"r")
            outfile = open(next_path + '.out', "w")
            newfield2(infile, outfile)


来源:https://stackoverflow.com/questions/16034364/how-to-read-all-files-in-one-folder-and-apply-a-function-over-them-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!