2017-09-25 14 views
1

목록 및 문자열 서식을 지정하고 새 파일에 변경 사항을 쓰는 데 문제가 있습니다. 내가 찾고 있습니다 : 모두 이전 및 다음 문자열은 이미 목록 및 문자열 형식 지정에 어려움 : txt 파일 가져 오기, 문자열 추가 및 새 파일에 쓰기

AFTER

  • 수입 txt 파일 내용 (문자열 값 목록)
  • STRINGS 전

    1. 문자열 경우 정의되고 모든 것이 새로운 파일에 기록됩니다!

      내 최종 목표는 txt 파일 (목록 포함)을 가져 와서 코드를 실행할 때 가져온 txt 파일의 목록 앞뒤에 미리 정의 된 문자열이있는 새 파일에 인쇄됩니다. 다음과 같이

      내 코드는 바로 지금입니다 :

      text_file = open(r"text_file path", "r") 
      lines = text_file.read().split(',') 
      lines.insert(0, "String Values Before") 
      lines.insert("String Values After") 
      text_file.close() 
      lines.write("new_file.txt", "w+") 
      

      문제는 지금은 문자열 목록에 분리되고 싶어 반면 나는 목록에 삽입하고 있다는 것입니다!

      나는 기록 된 파일이 여기에이 코드를 사용하여 콘솔에 같이하고 싶은 생산 할 수있었습니다 :

      FIRMNAME = "apple" 
      FILETYPE = "apple" 
      REPLYFILENAME = "apple" 
      SECMASTER = "apple" 
      PROGRAMNAME = "apple" 
      
      text_file = open(r"textfile path", "r+") 
      lines = text_file.readlines().split('\n') 
      
      print(("START-OF-FILE \nFIRMNAME= ") + FIRMNAME) 
      
      print(("FILETYPE= ") + FILETYPE) 
      
      print(("REPLYFILENAME= ") + REPLYFILENAME) 
      
      print(("SECMASTER= ") + SECMASTER) 
      
      print(("PROGRAMNAME= ") + PROGRAMNAME) 
      
      
      print("START-OF-FIELDS") 
      
      print("END-OF-FIELDS") 
      
      print("START-OF-DATA") 
      pprint.pprint(lines) 
      print("END-OF-DATA") 
      print("END-OF-FILE") 
      

      난 그냥 새 파일이 작성하는 방법을 알아낼 수 없습니다 ! 도움!

  • +0

    가 추가 모드와 –

    +0

    당신이 무엇을 의미합니까 줄 바꿈을 사용? 보여 주시겠습니까? 감사! : –

    +1

    'lines.write ("new_file.txt", "a")' –

    답변

    2

    당신은 이런 식으로 해결할 수 :

    newFile = 'your_new_file.txt' 
    oldFile = 'your_old_file.txt' 
    
    # Open the new text file 
    with open(newFile, 'w') as new_file: 
        # Open the old text file 
        with open(oldFile, 'r') as old_file: 
         # Write the line before the old content 
         new_file.write('Line before old content\n') 
    
         # Write old content 
         for line in old_file.readlines(): 
          new_file.write(line) 
    
         # Write line after old content 
         new_file.write('Line after old content') 
    
    +1

    감사합니다 mischi! 그것은 일했다! :) –

    1

    귀하의 lines이 방법 write이없는 타입 list,이다 변수입니다.
    insert에는 두 번째 호출이 부족한 위치가 필요합니다.

    당신은 그에 따라 접두사와 접미사 값으로 CONCAT 파일을 읽은 다음 적절한 출력 파일에 기록해야합니다 :

    with open("text_file_path", "r") as input_file: 
        text = input_file.read() 
    
    text = '\n'.join(("String Values Before", text, "String Values After")) 
    
    with open("new_file.txt", "w+") as output_file: 
        output_file.write(text) 
    
    1

    사용 pformat.
    pprint

    before_values = ["a", "b", "c"] 
    data = ["1", "2", "3"] 
    after_values = ["d", "e", "f"] 
    with open("outfile.txt", "w) as outfile: 
        outfile.write("\n".join(before_values)) # Write before values 
        outfile.write(pprint.pformat(data))  # Write data list 
        outfile.write("\n".join(after_values)) # Write after values 
    
    0

    당신은 당신이 인덱스를 제공해야하기 때문에 오류가 당신이 원래 insert 메소드를 호출있다; 그러나, 당신은 단지 결과리스트에 가입, 추가 및 파일에 쓸 수

    text_file = open(r"text_file path", "r") 
    lines = text_file.read().split(',') 
    lines.insert(0, "String Values Before") 
    lines.append("String Values After") 
    text_file.close() 
    new_file = open('text_file_path.txt', 'w') 
    new_file.write(','.join(lines)+'\n') 
    new_file.close()