2017-04-24 1 views
0

test1.properties 엔트리 키 1을 갖는 파일 = 200 test2.properties 갖는 엔트리 키 2 = 500파싱 특성 파이썬

files = ['test1.properties', test2.properties'] 

for file in files: 
    with open(file) as stream: 
    stream = StringIO("[top]\n" + stream.read()) 
    parser.readfp(stream) 
    print parser.items('top') 

[('KEY1', '200') ('키 2', '500 ')]

반복 중에 파일을 기반으로 기존 튜플 목록에 다른 항목을 추가하고 싶습니다. file1 항목은 test1.properties 튜플에만 추가하고 file2 항목은 test2.properties 튜플에만 추가해야합니다.

는 [("KEY1 ','200 ','FILE1 ') ('키 2 ','500 ','파일 2 ')]

답변

0

여기 해결책이다.

StringIO 오기 StringIO N = re.search ('(\ D +)'stream.name)로부터
import re 
files = ['test1.properties', 'test2.properties'] 
values = [] 
for file in files: 
    with open(file) as file_obj: 
    stream = StringIO("[top]\n" + file_obj.read()) 
    parser.readfp(stream) 
    n = re.search('(\d+)', file_obj.name).group(1) 
    values.append(parser.items('top') + ('file%s' % n,)) 

print(values) 
+0

는 .group (1) AttributeError :있는 StringIO 인스턴스가 더 속성 '이름' 이없는 파이썬 2.x를 인 – spiderman

+0

@spiderman'stream' 파일 포인터를'StringIO' 인스턴스로 오버라이드하고 있습니다. 이름을 바꾸고'file_pointer.name'을 사용하십시오. 나는 그것을 고칠 수있는 코드를 업데이트했다. –