将文本文件连接在一起(并排)

时间:2017-03-25 08:42:05

标签: python text concatenation

我有以下代码用于连接一系列文本文件。 但我希望文件中的数据放在旁边而不是前面的行下面,我该怎么做?

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)

1 个答案:

答案 0 :(得分: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',然后将第三个文件添加到此文件中,并再次将此文件保留为“concatenated.txt”,依此类推。