如何追加和前置到目录中每个文本文件的每一行?

时间:2017-06-27 04:38:08

标签: python

我在Python中提出了这个代码,它在目录中获取一个文本文件,并在每行前添加和添加输入。这是:

prefix = '111'
suffix = '222'

with open('source.txt', 'r') as src:
    with open('dest.txt', 'w') as dest:
       for line in src:
           dest.write('%s%s%s\n' % (prefix, line.rstrip('\n'), suffix))

所以,我想做同样类型的事情,但相反,我在目录中有一堆txt文件,每个文件包含几百行。

我希望它在该目录中的每个文件中的每一行附加和前置(如上所述)。

我该怎么做?

1 个答案:

答案 0 :(得分:0)

试试这个:

import os
directory = '/path/to/directory/'
prefix = '111'
suffix = '222'
# list comprehension for all files with a .txt extension
txt_files = [
  f
  for f in os.listdir(directory)
  if os.path.isfile(os.path.join(directory, f)) and '.txt' in f
]
for txt in txt_files:
  with open(os.path.join(directory, txt), 'r') as src:
    # writing file to same name with added .dest extension
    with open(os.path.join(directory, txt + '.dest', 'w') as dest:
      for line in src:
        dest.write('%s%s%s\n' % (prefix, line, suffix))

我假设你想对这些文件做其他事情;否则使用findsed做同样的事情要简单得多。