Python's code for merging multiple text files into one text (easy to search)

  • 2020-04-02 09:28:24
  • OfStack

However, when a book after learning, the general technology and functions have an impression, suddenly want to find an instance of a function code, but feel very difficult, because a book source directory is very long, often have dozens or even hundreds of source code files, want to find the function you want to instance is not easy to say?

So here is to all the source code by directory and file name as a label, all merged into one place, so as to facilitate a quick search. Look, no, look for the next... So you can quickly find the example you want, very convenient. Of course, separate source code files are still useful and can be retained as well. After merging the source file is not large, n*100KB, open and search is very fast. You can merge all the instances of the same programming language into one file in this way, and the search efficiency will be greatly improved.

Note: after saving the code, copy the source file to the directory, and all directories and subdirectories in the same directory will be searched. You can add suffixes to limit the content of a file to a certain format. The source code is as follows, please save after copying:
 
# -*- coding: utf-8 -*- 

import os,sys 
info = os.getcwd() 
fout = open('note.tpy', 'w') #  Merge content into this file  

def writeintofile(info): 
fin = open(info) 
strinfo = fin.read() 
#  using ## As an addition to the label, you can use others as well  
fout.write('n##n') 
fout.write('## '+info[-30:].encode('utf-8')) 
fout.write('n##nn') 
fout.write(strinfo) 
fin.close() 


for root, dirs, files in os.walk(info): 
if len(dirs)==0: 
for fl in files: 
info = "%s%s" % (root,fl) 
if info[-2:] == 'py': #  Just name the suffix py File content merge  
writeintofile(info) 

fout.close() 

If you don't want to merge content and just want to get a list of file names, you can. Here's the code. For example, some authors use this feature to generate a list of source files for themselves, which is useful.

Source code:
 
# -*- coding: utf-8 -*- 
''' 
 This procedure automatically searches the specified directory , 
 Print the full file name of all files to the specified file  
''' 
import os,sys 
export = "" 
i=1 
for root, dirs, files in os.walk(r'..'): 
#r'.' Represents all listings in the current directory  
#.. Represents other directories that are parallel , A lot more  
export += "--%s--n%snn%snn" % (i,root,'n'.join(files)) 
i=i+1 
fp = open('cdcfile-4.txt', 'w') 
fp.write(export) 
fp.close() 

Related articles: