在数据处理或批量文件处理中,常有对多个小文件合并到一个大文件中的需求,以下是两段小程序,记录在此以备用。
这是我用VB写的程序,电脑上没有编程软件时可用Excel,在Excel的“宏”模块写下如下代码来执行,实现把某文件夹下的所有文本文件合并到一个aaa3.txt文件中,具体文件夹或输出格式可照程序修改:
Sub Macro1()
Dim fso, fd, fi, ffs
Dim FileNumber, i, j As Integer
Dim Mystring, strSortFile() As String
FileCount = 0
FileNumber = FreeFile
Set fso =CreateObject("Scripting.filesystemobject")
Set fd =fso.getfolder("E:\prg_python\temp")
Set ffs = fd.Files
For Each fi In ffs
FileCount = FileCount + 1
Next
If FileCount = 0 Then GoTo ErrPrc
Dim Aaa As String
ReDim strSortFile(0 To FileCount)
For Each fi In ffs
Aaa = fi.Name
If Aaa > strSortFile(i) Then
strSortFile(i + 1) = Aaa
Else
j = i
Do
strSortFile(j + 1) =strSortFile(j)
j = j - 1
Loop Until Aaa >= strSortFile(j)
strSortFile(j + 1) = Aaa
End If
i = i + 1
Next
j = 1
Open"E:\prg_python\temp\aaa3.txt" For Output As #5
For i = 1 To FileCount
Open fd & "\" & strSortFile(i) For Input As FileNumber
Print #5, "__________________"
Print #5, strSortFile(i)
Print #5, "______________"
While Not EOF(FileNumber)
Line Input #FileNumber, Mystring
Print #5, Mystring
Wend
Close #FileNumber
j= j + 1
Next i
Close #5
Exit Sub
ErrPrc:
MsgBox "File Error" & Chr(10) & "Select CorrectFile Directory ", , "ERROR"
End Sub
以下是用Perl来实现同样的功能,把文件某文件夹下.py文件合并到kang02.txt中,程序相对就短一点了。
$aa="E:\\prg_python";
chdir $aa;
@FILES=`dir *.py/b`;
my $fff;
open(F_ALL,">kang02.txt");
for($j=0;$j<@FILES;$j++){
$fff=$FILES[$j]; chomp($fff);
print F_ALL"#============".$fff."=========".$j."====\n";
open(F_PL,"<$fff") or die"cannot open\n";
while($line=<F_PL>){
print F_ALL $line;
}
close(F_PL);
}
close(F_ALL);
print "\n";
转载本文请联系原作者获取授权,同时请注明本文来自康建科学网博客。
链接地址:https://wap.sciencenet.cn/blog-797552-1096602.html?mobile=1
收藏