Los archivos de texto de Python se fusionan desde el subdirectorio [cerrado]
Frecuentes
Visto 425 veces
-3
I am having many text files scattered across many subdirectories. Just want to have compiled single aggregate text file. My requirement is to generate text file that should have directory structure including file name as prefix for each line. TIA
1 Respuestas
2
import os
root = './'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('master.txt','w')
for path,f_name in files:
in_file = open('%s/%s'%(path,f_name), 'r')
# write out root/path/to/file (space) file_contents
for line in in_file:
out_file.write('%s/%s %s'%(path,f_name,line))
in_file.close()
# enter new line after each file
out_file.write('\n')
out_file.close()
if you only want some files from the tree rooted at root
change the third line to
# only take .txt files from the directory tree
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list if f.endswith('.txt')]
Respondido 28 ago 12, 12:08
Utilice las os.path
for extracting the extensions and joining paths... - Katriel
10x, @MattiLyra i am getting syntax error for the 'in', in = os.open('%s/%s' % (path, f_name), 'r'). BTW files are in C:\\Tasks\\ folder. - user1582596
rather than using in and out use in_file and out_file - geo_pythoncl
in both cases don't use os.open() use just open() - geo_pythoncl
@user1582596 see updated code above - Matti Lira
No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas python python-3.x or haz tu propia pregunta.
Your question lacks any sign of research, anything you've done yourself to try and solve the problem, things you've looked at, etc. - cfi