Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialdmitriy ignatiev
Python Web Development Techdegree Student 1,789 Pointsmake a additional unique text file for each sentences throught the loop
Hi, could you expain if for expamle i have throught loop 5 sentences. and i need to create automatically each time new txt file for each my sentences throught for a loop?
3 Answers
Kenneth Love
Treehouse Guest TeacherYeah, you're writing to the same file each time. You'll need to write a different file on each loop.
sentences = ["first", "second", "third"]
files = ["file1.txt", "file2.txt", "file3.txt"]
for sentence, file in zip(sentences, files):
open(file, "a").write(sentence)
Kenneth Love
Treehouse Guest TeacherYou'd need to open()
and write()
to a file for each step of a loop through a list of sentences.
dmitriy ignatiev
Python Web Development Techdegree Student 1,789 PointsKenneth let me refrase the question. I have code below, but he just create a file one time (only one file 'new_txt') and the file include all my_sentences through the loop. But i need one sentences in one txt file. If i have a list with 3 items i need 3 txt.file with one item in each txt.file Please clarify how it could be done. Thanks ''' my_sentenses = ['first sentense', 'second sent', 'third sent']
for sentenses in my_sentenses: with open ('new_txt.txt', 'a') as file: file.write(sentenses)'''