Batch Append Files by File Names

Question

There are hundreds of files in the current path. The file names are like this: 12345.txt, 12346.txt, 12347.txt, 2013070312345.txt, 2013070312346.txt and 2013070312346.txt. I want to run a Python program to append contents of 12345.txt to 2013070312345.txt and contents of 12346.txt to 2013070312346.txt, and so on. But how can I tell the program to find the right file to append? Thanks.

 

Answer

To do it in Python, you need to get all file names under the current directory using listdir()method, find file names whose lengths are greater than 9 iteratively, and then perform read and append. Since Python support of file processing is low-level, the code needs to handle many details, which makes it very lengthy. We can handle the question in SPL (Structured Process Language) with several lines code:

A

B

1

=directory("E:\\test").select(len(~)>9)

2

for A1

=file("E:\\test\\"+   right(A2,9)).read()

3

=file("E:\\   test\\"+ A2).write@a(B2)

A1: Find txt files whose names are greater than 9.

A2-B3: Run a loop to read each of A1’s file names and then read corresponding file with a shorter name to append to it.