2017-03-25 1 views
0

일련의 텍스트 파일을 연결하는 데 다음 코드가 있습니다. 하지만 파일의 데이터를 이전 줄 아래가 아닌 아래에 배치하려면 어떻게해야합니까?서로 나란히있는 텍스트 파일 연결 (나란히)

for dir in list(subdirs): 
    splitdir = dir.split('/') 
    # YOU WILL NEED TO EDIT THIS TO GRAB sub001 
    splitdir_sub = splitdir[5] 
    subnum=splitdir_sub[-4:] 
    # YOU WILL ALSO NEED TO EDIT THIS TO GRAB THE PART WITH THE RUNNUM 
    splitdir_run = splitdir[8] 
    runnum=splitdir_run[-1:] 
    print("marging subject %s Run %s"%(subnum, runnum)) 
    filenames = ['/home/navotn/Exp5/participants/%s/preprocessed/1lev/block%sn.feat/white_matter.txt'%(subnum, runnum), '/home/navotn/Exp5/participants/%s/preprocessed/PPFSL/block%s/motion_assess/confound.txt'%(subnum, runnum)] 
    with open("%s/%s/preprocessed/PPFSL/block%s/motion_assess/confoundWM.txt"%(fsfdir, subnum, runnum), 'w') as outfile: 
     for fname in filenames: 
      with open(fname) as infile: 
       for line in infile: 
        outfile.write(line) 
+0

파일이 빈 줄 바꿈으로 끝나나요? 왜냐하면 그것이 이유 일 수도 있기 때문입니다. – Ibrahim

+0

@Navot Naor 파일 쓰기 'w'대신 파일 'a'를 추가하십시오. – Len

답변

0

이 코드는 입력 파일의 줄 수가 동일한 경우 필요한 것을 제공 할 수 있습니다.

import os 

fileNames = os.listdir('concatenate') 
os.chdir('concatenate') 
previous = fileNames[0] 
for fileName in os.listdir('.')[1:]: 
    with open(previous) as oldConcatenate, open(fileName) as nextFile, open('new.txt', 'w') as newConcatenate: 
     while True: 
      oldLine = oldConcatenate.readline().strip() 
      if not oldLine: 
       break 
      nextLine = nextFile.readline().strip() 
      newConcatenate.write(oldLine + nextLine + '\n') 
    if previous != fileNames[0]: 
     os.remove('concatenated.txt') 
    os.rename('new.txt', 'concatenated.txt') 
    previous = 'concatenated.txt' 

코드가 처음에 두 번째 파일을 연결하고 파일 'concatenated.txt'이 후 다시 제 3 파일에 추가하고 그래서 "concatenated.txt '및이 파일을 계속 유지한다는.

관련 문제