2013-04-16 2 views
1

하나의 폴더에있는 모든 파일에 대해 기능을 실행하고 그 중 새 파일을 만들고 싶습니다. 한 파일에 대한 코드를 작성했습니다. 친절하게 도와 주시면 감사하겠습니다. ':/사가/데이터/2006last/E'폴더를 편집 확장자를 가진 새 파일을 만들하나의 폴더에있는 모든 파일을 읽고 파이썬에서 함수를 적용하는 방법은 무엇입니까?

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

나는 모든 파일을 변경하고 싶습니다.

+0

당신이 들여 쓰기 문제를 해결하시기 바랍니다 수, 난 당신이 제대로 여부를 – jamylak

+0

당신이 들여 무엇을 의미합니까 미안했던 whethere 확실하지 않다? –

+0

왼쪽부터 각 줄의 공백 수 – jamylak

답변

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

os.listdir()을 사용하면 디렉토리의 모든 파일을 나열 할 수 있습니다. 이 함수는 전체 경로가 아닌 파일 이름 만 반환합니다. os.path module 필요에 따라 파일 이름을 구성 할 수있는 도구를 제공합니다 :

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) 
+0

outfile을 'w'모드로 열어야합니다. – FrostNovaZzz

+0

@FrostNovaZzz : Duh .. 고마워. –

+0

대단히 도움을 주셔서 감사합니다. '기본 및 확장'과 splitext에 대해 설명해 주시겠습니까? –

관련 문제