2014-12-07 3 views
0

"example"이라는 문자열로 시작하고 숫자가 끝나는 많은 파일이 있습니다 (순서가 중요합니다). 나는 순서대로 모든 파일의 이름을 바꾸고 example1, example2, example3, ..., example150 순으로 파일을 읽는 대신 example1, example10, example100, example 101 등의 순서로 파일을 읽습니다. 예제 102, ... 그리고이 프로세스를 반복합니다. 순차적으로 파일을 읽으려면 어떻게 변경합니까? 감사!Python 변경 번호가 매겨진 파일을 읽는 방법

+0

두 가지 선택 : 당신의 문제를 들어 정렬 키 당신의 정수로 문자열을 설정하는 int()을 사용하는 모든 텍스트를 제거 얻을 수 있고 (example000, example001 등) 0 숫자를 선도해야 할 파일의 이름을 바꿉니다 어휘 적으로 대신 이름을 숫자순으로 정렬하도록 정렬을 수정하십시오. 특정 도움이 필요하면 특정 코드를 게시하십시오. –

답변

1

이와 비슷한?

n = .. # amount of files 
for i in range(0, n) : 
    f = open("example" + str(i), "r") 
    # do something with your file 
    f.close() 
+0

완벽하고 정확하게 내가 찾고있는 것이 었습니다. 고맙습니다! – Code4Days

0
files = ['example1.txt','example2.txt', 'example10.txt','example11.txt', 'example100.txt', 'example101.txt', 'example102.txt'] 

def sort_numericly(file_list,prefix,sufix): 
    new_file_list = [] 
    for f in file_list: 
     f = f.strip(prefix).strip(sufix) 
     new_file_list.append(int(f)) 
    return [prefix+ str(f) + sufixfor f in sorted(new_file_list)] 

print sorted(files) 
print sort_numericly(files,'example','.txt') 

출력 :

['example1.txt', 'example10.txt', 'example100.txt', 'example101.txt', 'example102.txt', 'example11.txt', 'example2.txt'] 
['example1.txt', 'example2.txt', 'example10.txt', 'example11.txt', 'example100.txt', 'example101.txt', 'example102.txt'] 
1

정렬은 정렬 키를 설정하는데 사용될 수있는 인자를 key.

for files in sorted(files, 
        key=lambda f: int(f.replace('example','').replace('.txt',''))): 
    # process the file 
+2

대신 .strip()을 사용하십시오.) –

+0

f.rodrigues가 맞습니다. replace :-) 대신'f.strip ('example.txt')'를 쓸 수있다. 보다 깔끔하고보다 일반적인 해결책은 정규식을 사용하는 것입니다 :'import re; ... int (re.sub (r '\ D', '', f))' –

관련 문제