1

我想对一个文件夹中的所有文件运行一个函数并从中创建新文件。我已将一个文件的代码放在下面。如果你能帮助我,我将不胜感激。

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/”文件夹中的所有文件并创建带有编辑扩展名的新文件。

4

2 回答 2

4

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

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)
于 2013-04-16T10:26:57.910 回答
0
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)
于 2013-04-16T10:26:35.817 回答