如何读取一个文件夹中的所有文件并在python中对其应用函数? [英] How to read all files in one folder and apply a function over them in python?

查看:192
本文介绍了如何读取一个文件夹中的所有文件并在python中对其应用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对一个文件夹中的所有文件运行一个函数,并从中创建新文件。我将代码放在一个文件箱中。

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")

想要更改 E:/ SAGA / data / 2006last /文件夹中的所有文件,并创建带有编辑扩展名的新文件。

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

推荐答案

使用 os.listdir()列出目录中的所有文件。该函数仅返回文件名,而不返回完整路径。 os.path 模块为您提供了根据需要构造文件名的工具:

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)

这篇关于如何读取一个文件夹中的所有文件并在python中对其应用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆