Python: analiza una lista grande en archivos de texto separados por nombre y contenido

What I am trying to achieve is to separate up a list of entries in a single file into multiple files as follows.


And save the single line entries into files, where a new file would look like this

For example the first entry-

Filename would be thing1.txt.

Contents in the file would be:

[some static text common to all files][more static content]

And have this run as a loop on all entries in the list file until exhausting the list. Not sure if a for loop will work here, or a while loop.

I've just begun learning python, and some of these functions (creating files, specifying filenames) are still foreign to me.

preguntado el 01 de febrero de 12 a las 22:02

It's not at all clear to me what you are trying to accomplish, and what question you are asking. Please give an example of 3-6 lines of the input file. Are the strings,, etc. constants known at the time of coding, or run-time parameters, or something the code determines by examining the input file? Have you tried working through the Tutorial de Python or other tutorials from the Guía para principiantes list, to learn the basics of reading files and looping? -

Sorry for the lack of clarity, I see where I should have elaborated more now. I have a text file that is just a list of URLs. I want to parse that specific text file, using each entry in the list seperated by returns (or \n) into a file just for that entry, containing the entry and some additional text within the file, and then secondarily, saving the file using a filename based on that entry. And finally loop it all so it does this for the entire list inside the primary text doc. My general question is, point me in the right direction as to how to get this done, which you did so thanks! -

1 Respuestas

I am telling you for a single file but for your case you can iterate over your list para lograr lo mismo.

Voy a usar I/O module for file handling y re módulo extraer thing1 from your link.

>>> st = ""
>>> filename = re.findall(r"/(\w+).",st)
>>> filename
>>> filename = "".join(filename) + '.txt'
>>> filename
>>> f = open(filename,'w')
>>> f.writelines(st)

También puede pasar un list a writelines.

mylist = ["some static text common to all files",st,"more static content"]

Respondido 02 Feb 12, 02:02

Thanks Ranrag! Very helpful. - user1183802

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.