2016-10-10 4 views
2

디렉토리에있는 일부 파일의 이름으로 목록의 요소를 지정하려고하는데 지금까지 디렉토리에서 각 파일의 이름을 복구하고 목록으로 반환하는 함수를 만들었습니다.목록의 요소를 파이썬에서 파일 이름으로 할당하는 방법은 무엇입니까?

def retrive(directory_path): 
    path_names = [] 
    for filename in sorted(glob.glob(os.path.join(directory_path, '*.pdf'))): 
     retrieved_files = filename.split('/')[-1] 
     path_names.append(retrieved_files) 
    print (path_names) 

목록에서 위의 함수가 반환 각 파일의 이름, 나는 다른 디렉토리에 파일을 작성하고 다음과 같이

마지막으로
path = os.path.join(new_dir_path, "list%d.txt" % i) 
    #This is the path of each new file: 
    #print(path) 
    with codecs.open(path, "w", encoding='utf8') as filename: 
     for item in [a_list]: 
      filename.write(item+"\n") 

, 내 질문은 : 나는의 이름으로 할당하는 방법을 각 파일, 각 요소 path_names?, 다음 줄과 같은 내용 :

path = os.path.join(new_dir_path, "list%d.txt" % i) 

또한 format() 기능을 사용하려고했습니다. 그러나 나는 여전히 각 파일에 정확한 이름을 할당 할 수 없습니다.

def transform_directoy(input_directory, output_directory):  
    import codecs, glob, os 
    from tika import parser 
    all_texts = [] 
    for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): 
     parsed = parser.from_file(filename) 
     texts = parsed['content'] 
     all_texts.append(texts) 

    for i , a_list in enumerate(all_texts): 
     new_dir_path = output_directory 


     #print(new_dir_path) 
     path = os.path.join(new_dir_path, "list%d.txt" % i) 
     with codecs.open(path, "w", encoding='utf8') as filename: 
      for item in [a_list]: 
       filename.write(item+"\n")   

원하는 출력은 각 처리의 실제 파일 이름으로 구성된다 :

은 여기에 전체 스크립트이다.

+2

은 왜이다 : 영업 이익이 있다는 것을 모든 있었다면 내가 그렇게 간다,이 코드를 작성합니다 방법을 묻는 원하는 파일을 열 때 파일 이름을 열면됩니까? – TigerhawkT3

+0

그리고 왜'open()'대신에'codecs.open()'을 사용하고 있습니까? –

+0

도움을 주셔서 감사합니다. 왜냐하면 내가 다시 작성하고 다른 형식으로 처리하기 때문입니다. @JohnGordon – tumbleweed

답변

1

당신은 거의 다 :

for path_name in path_names: 
    path = os.path.join(new_dir_path, "list%s.txt" % path_name) 
    #This is the path of each new file: 
    #print(path) 
    with codecs.open(path, "w", encoding='utf8') as f: 
     for item in [a_list]: 
      f.write(item+"\n") 

업데이트를 업데이트 코드 샘플에 따라. 여기에 다른 루프를 사용하고 있으며 두 루프 사이에서 처리하지 않는 한 이상적이지 않습니다. 이 구조를 유지할 것이므로 각 내용 블록을 원본 파일 이름과 연결해야합니다. 가장 좋은 구조는 dict이며, 순서가 중요 할 경우 OrderedDict을 사용합니다. 이제 OrderedDict의 파일 이름, 내용 쌍을 반복 할 때 새 파일 유형과 일치하도록 파일의 확장자를 변경하려고합니다. 운 좋게도, 파이썬은 os.path 모듈에서 파일/경로 조작을위한 훌륭한 유틸리티를 가지고 있습니다. os.path.basename은 파일에서 디렉토리를 제거하는 데 사용할 수 있으며 os.path.splitext은 파일 이름에서 확장자를 제거합니다. 확장명이없는 파일 이름 만 가져오고 .txt을 추가하여 새 파일 형식을 지정하기 위해 두 파일을 모두 사용합니다. 모두 함께 퍼팅, 우리가 얻을 :

def transform_directoy(input_directory, output_directory):  
    import codecs, glob, os 
    from collections import OrderedDict 
    from tika import parser 
    all_texts = OrderedDict() 
    for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): 
     parsed = parser.from_file(filename) 
     filename = os.path.basename(filename) 
     texts = parsed['content'] 
     all_texts[filename] = texts 

    for i, (original_filename, a_list) in enumerate(all_texts.items()): 
     new_filename, _ = os.path.splitext(original_filename) 
     new_filename += '.txt' 
     new_dir_path = output_directory 

     #print(new_dir_path) 
     path = os.path.join(new_dir_path, new_filename) 
     # Print out the name of the file we are processing 
     print('Transforming %s => %s' % (original_filename, path,)) 
     with codecs.open(path, "w", encoding='utf8') as filename: 
      for item in [a_list]: 
       filename.write(item+"\n") 

두 번째 업데이트 :

# move imports to top of file: PEP 8 
import codecs, glob, os 
from tika import parser 

def transform_directoy(input_directory, output_directory):  
    for filename in sorted(glob.glob(os.path.join(input_directory, '*.pdf'))): 
     parsed = parser.from_file(filename) 
     parsed_content = parsed['content'] 
     original_filename = os.path.basename(filename) 
     new_filename, _ = os.path.splitext(original_filename) 
     new_filename += '.txt' 
     path = os.path.join(output_directory, new_filename) 
     # Print out the name of the file we are processing 
     print('Transforming %s => %s' % (original_filename, path,)) 
     # no need for a second loop since we can piggy back off the first loop 
     with codecs.open(path, "w", encoding='utf8') as filename: 
      # No need for a for loop here since our list only has one item 
      filename.write(parsed_content) 
      filename.write("\n") 
+0

도움을 주셔서 감사합니다. 그러나 나는 파일의 원래 이름을 보존하고 있지 않다. 또한 파일을 다시 작성할 때 하나의 파일이 누락되었다. 감사! – tumbleweed

+1

귀하의 질문은 문자 그대로였습니다 :'마지막으로, 내 질문은 : 각 파일의 이름으로 path_names의 각 요소를 어떻게 할당 할 수 있습니까? '라는 것이 었습니다. 원래 파일 이름을 유지하려고합니다.따라서 질문을 편집하여 답변을 원하는 질문을 정확히 기재하고 전체 * 코드를 게시하십시오. – 2ps

+0

도움 주셔서 감사합니다 2ps 모든 스크립트로 질문을 업데이트했습니다. 감사합니다! – tumbleweed

관련 문제