TheLousyLinguist
TheLousyLinguist

Reputation: 85

how to automate multiple file generation in Python

I want to automate multiple file generation. I have a working Python script to generate a single file with sentences that mimic a domain of language I'm interested in (code from here). The code below takes the text my_domain.txt as input, trains a Markov language model on it, then outputs a file with 10 fake sentences that read pretty similarly to the ones in the input text.

import pandas as pd
import markovify #Markov Chain Generator
import sys

with open(r'/my_domain.txt') as f:
    text = f.read()

text_model = markovify.Text(text) #creates a language model from the input text

sys.stdout = open('fake.txt', 'w') #redirects my print() statement below to a file

for i in range(10): #10 lines of fake sentences.
    print(text_model.make_sentence())

What I want to do now is use this method to generate 1000+ files, each with a slightly unique name, like this:

fake1.txt

fake2.txt

fake3.txt

I'm guessing that I may need a different method of printing to a file. But when I search on techniques, I don't find anything that helps me run the markovify method repeatedly AND gives unique names to each successive output file.

Upvotes: 1

Views: 391

Answers (1)

Patrick Artner
Patrick Artner

Reputation: 51653

Use a loop that creates filenames, use with open(..) syntax to make sure they get closed ok even if exception arises.

for nr in range(100):
    with open("file{:04}.txt".format(nr), "w") as f:
        for i in range(10): #10 lines of fake sentences.
            f.write(text_model.make_sentence() + "\n")

Upvotes: 2

Related Questions