stop while loop when the text ends Unicorn Meta Zoo #1: Why another podcast? Announcing the arrival of Valued Associate #679: Cesar Manara Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!When to use double or single quotes in JavaScript?Select <a> which href ends with some stringAccessing the index in 'for' loops?Emulate a do-while loop in Python?Syntax for a single-line Bash infinite while loopIterating over dictionaries using 'for' loopsC++ For Loop inside a While loopWhy is this a never-ending loop?Which is faster: while(1) or while(2)?Python homework with while loops to print output

Protagonist's race is hidden - should I reveal it?

How to keep bees out of canned beverages?

What happened to Viserion in Season 7?

When speaking, how do you change your mind mid-sentence?

Israeli soda type drink

What is the numbering system used for the DSN dishes?

What does the black goddess statue do and what is it?

Are there existing rules/lore for MTG planeswalkers?

Does Prince Arnaud cause someone holding the Princess to lose?

What is the ongoing value of the Kanban board to the developers as opposed to management

Why aren't road bicycle wheels tiny?

/bin/ls sorts differently than just ls

Can gravitational waves pass through a black hole?

What's called a person who works as someone who puts products on shelves in stores?

Is it accepted to use working hours to read general interest books?

Raising a bilingual kid. When should we introduce the majority language?

When I export an AI 300x60 art board it saves with bigger dimensions

When does Bran Stark remember Jamie pushing him?

Why is arima in R one time step off?

How would it unbalance gameplay to rule that Weapon Master allows for picking a fighting style?

Has a Nobel Peace laureate ever been accused of war crimes?

Is it OK if I do not take the receipt in Germany?

What is /etc/mtab in Linux?

Page Layouts : 1 column , 2 columns-left , 2 columns-right , 3 column



stop while loop when the text ends



Unicorn Meta Zoo #1: Why another podcast?
Announcing the arrival of Valued Associate #679: Cesar Manara
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!When to use double or single quotes in JavaScript?Select <a> which href ends with some stringAccessing the index in 'for' loops?Emulate a do-while loop in Python?Syntax for a single-line Bash infinite while loopIterating over dictionaries using 'for' loopsC++ For Loop inside a While loopWhy is this a never-ending loop?Which is faster: while(1) or while(2)?Python homework with while loops to print output



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-1















I have a program that loops through the lines of a book to match some tags I've created indicating the start and the end of each chapter of this book. I want to separate each chapter into a different file. The program finds each chapter and asks the user to name the file, then it continues until the next chapter and so on. I don't know exactly where to put my "break" or something that could stop my loop. The program runs well but when it reaches the last chapter it goes back to the first chapter. I want to stop the loop and terminate the program when the tags and the chapters finish and also print something like "End of chapters". Can anyone help me with that? The code is below:



import re
def separate_files ():
with open('sample.txt') as file:
chapters = file.readlines()



pat=re.compile(r"[@introS].[@introEnd@]")
reg= list(filter(pat.match, chapters))
txt=' '

while True:
for i in chapters:
if i in reg:
print(i)
inp=input("write text a file? Y|N: ")
if inp =='Y':
txt=i
file_name=input('Name your file: ')
out_file=open(file_name,'w')
out_file.write(txt)
out_file.close()
print('text', inp, 'written to a file')
elif inp =='N':
break
else:
continue
else:
continue


separate_files()









share|improve this question






















  • "but when it reaches the last chapter it goes back to the first chapter"... Yes. Because the for i in chapters: loop ends and the external while repeats everything. Just remove the while (and while you're at it, also the else: continue at the end, which I'm 200% sure it's wrongly put there)

    – GPhilo
    Mar 22 at 15:11












  • Using "While True" will never end unless you break it yourself, I would recommend finding an actual true/false conditional check to use with your while statement so the looping ends when that condition is false. Or you could just remove the while since you are already looping over the data with your "for i in chapters" statement.

    – DrCord
    Mar 22 at 15:11






  • 1





    Is the while loop supposed to be inside separate_files? (Seems so, since otherwise chapters isn't defined.)

    – chepner
    Mar 22 at 15:12











  • @GPhilo, ok! I will try to remove the while True.

    – Natália Resende
    Mar 22 at 15:18











  • That's not the only error you have in the code, but you can start from there. As chepner pointed out, chapters is not defined anywhere

    – GPhilo
    Mar 22 at 15:20

















-1















I have a program that loops through the lines of a book to match some tags I've created indicating the start and the end of each chapter of this book. I want to separate each chapter into a different file. The program finds each chapter and asks the user to name the file, then it continues until the next chapter and so on. I don't know exactly where to put my "break" or something that could stop my loop. The program runs well but when it reaches the last chapter it goes back to the first chapter. I want to stop the loop and terminate the program when the tags and the chapters finish and also print something like "End of chapters". Can anyone help me with that? The code is below:



import re
def separate_files ():
with open('sample.txt') as file:
chapters = file.readlines()



pat=re.compile(r"[@introS].[@introEnd@]")
reg= list(filter(pat.match, chapters))
txt=' '

while True:
for i in chapters:
if i in reg:
print(i)
inp=input("write text a file? Y|N: ")
if inp =='Y':
txt=i
file_name=input('Name your file: ')
out_file=open(file_name,'w')
out_file.write(txt)
out_file.close()
print('text', inp, 'written to a file')
elif inp =='N':
break
else:
continue
else:
continue


separate_files()









share|improve this question






















  • "but when it reaches the last chapter it goes back to the first chapter"... Yes. Because the for i in chapters: loop ends and the external while repeats everything. Just remove the while (and while you're at it, also the else: continue at the end, which I'm 200% sure it's wrongly put there)

    – GPhilo
    Mar 22 at 15:11












  • Using "While True" will never end unless you break it yourself, I would recommend finding an actual true/false conditional check to use with your while statement so the looping ends when that condition is false. Or you could just remove the while since you are already looping over the data with your "for i in chapters" statement.

    – DrCord
    Mar 22 at 15:11






  • 1





    Is the while loop supposed to be inside separate_files? (Seems so, since otherwise chapters isn't defined.)

    – chepner
    Mar 22 at 15:12











  • @GPhilo, ok! I will try to remove the while True.

    – Natália Resende
    Mar 22 at 15:18











  • That's not the only error you have in the code, but you can start from there. As chepner pointed out, chapters is not defined anywhere

    – GPhilo
    Mar 22 at 15:20













-1












-1








-1








I have a program that loops through the lines of a book to match some tags I've created indicating the start and the end of each chapter of this book. I want to separate each chapter into a different file. The program finds each chapter and asks the user to name the file, then it continues until the next chapter and so on. I don't know exactly where to put my "break" or something that could stop my loop. The program runs well but when it reaches the last chapter it goes back to the first chapter. I want to stop the loop and terminate the program when the tags and the chapters finish and also print something like "End of chapters". Can anyone help me with that? The code is below:



import re
def separate_files ():
with open('sample.txt') as file:
chapters = file.readlines()



pat=re.compile(r"[@introS].[@introEnd@]")
reg= list(filter(pat.match, chapters))
txt=' '

while True:
for i in chapters:
if i in reg:
print(i)
inp=input("write text a file? Y|N: ")
if inp =='Y':
txt=i
file_name=input('Name your file: ')
out_file=open(file_name,'w')
out_file.write(txt)
out_file.close()
print('text', inp, 'written to a file')
elif inp =='N':
break
else:
continue
else:
continue


separate_files()









share|improve this question














I have a program that loops through the lines of a book to match some tags I've created indicating the start and the end of each chapter of this book. I want to separate each chapter into a different file. The program finds each chapter and asks the user to name the file, then it continues until the next chapter and so on. I don't know exactly where to put my "break" or something that could stop my loop. The program runs well but when it reaches the last chapter it goes back to the first chapter. I want to stop the loop and terminate the program when the tags and the chapters finish and also print something like "End of chapters". Can anyone help me with that? The code is below:



import re
def separate_files ():
with open('sample.txt') as file:
chapters = file.readlines()



pat=re.compile(r"[@introS].[@introEnd@]")
reg= list(filter(pat.match, chapters))
txt=' '

while True:
for i in chapters:
if i in reg:
print(i)
inp=input("write text a file? Y|N: ")
if inp =='Y':
txt=i
file_name=input('Name your file: ')
out_file=open(file_name,'w')
out_file.write(txt)
out_file.close()
print('text', inp, 'written to a file')
elif inp =='N':
break
else:
continue
else:
continue


separate_files()






python string while-loop






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 15:08









Natália ResendeNatália Resende

256




256












  • "but when it reaches the last chapter it goes back to the first chapter"... Yes. Because the for i in chapters: loop ends and the external while repeats everything. Just remove the while (and while you're at it, also the else: continue at the end, which I'm 200% sure it's wrongly put there)

    – GPhilo
    Mar 22 at 15:11












  • Using "While True" will never end unless you break it yourself, I would recommend finding an actual true/false conditional check to use with your while statement so the looping ends when that condition is false. Or you could just remove the while since you are already looping over the data with your "for i in chapters" statement.

    – DrCord
    Mar 22 at 15:11






  • 1





    Is the while loop supposed to be inside separate_files? (Seems so, since otherwise chapters isn't defined.)

    – chepner
    Mar 22 at 15:12











  • @GPhilo, ok! I will try to remove the while True.

    – Natália Resende
    Mar 22 at 15:18











  • That's not the only error you have in the code, but you can start from there. As chepner pointed out, chapters is not defined anywhere

    – GPhilo
    Mar 22 at 15:20

















  • "but when it reaches the last chapter it goes back to the first chapter"... Yes. Because the for i in chapters: loop ends and the external while repeats everything. Just remove the while (and while you're at it, also the else: continue at the end, which I'm 200% sure it's wrongly put there)

    – GPhilo
    Mar 22 at 15:11












  • Using "While True" will never end unless you break it yourself, I would recommend finding an actual true/false conditional check to use with your while statement so the looping ends when that condition is false. Or you could just remove the while since you are already looping over the data with your "for i in chapters" statement.

    – DrCord
    Mar 22 at 15:11






  • 1





    Is the while loop supposed to be inside separate_files? (Seems so, since otherwise chapters isn't defined.)

    – chepner
    Mar 22 at 15:12











  • @GPhilo, ok! I will try to remove the while True.

    – Natália Resende
    Mar 22 at 15:18











  • That's not the only error you have in the code, but you can start from there. As chepner pointed out, chapters is not defined anywhere

    – GPhilo
    Mar 22 at 15:20
















"but when it reaches the last chapter it goes back to the first chapter"... Yes. Because the for i in chapters: loop ends and the external while repeats everything. Just remove the while (and while you're at it, also the else: continue at the end, which I'm 200% sure it's wrongly put there)

– GPhilo
Mar 22 at 15:11






"but when it reaches the last chapter it goes back to the first chapter"... Yes. Because the for i in chapters: loop ends and the external while repeats everything. Just remove the while (and while you're at it, also the else: continue at the end, which I'm 200% sure it's wrongly put there)

– GPhilo
Mar 22 at 15:11














Using "While True" will never end unless you break it yourself, I would recommend finding an actual true/false conditional check to use with your while statement so the looping ends when that condition is false. Or you could just remove the while since you are already looping over the data with your "for i in chapters" statement.

– DrCord
Mar 22 at 15:11





Using "While True" will never end unless you break it yourself, I would recommend finding an actual true/false conditional check to use with your while statement so the looping ends when that condition is false. Or you could just remove the while since you are already looping over the data with your "for i in chapters" statement.

– DrCord
Mar 22 at 15:11




1




1





Is the while loop supposed to be inside separate_files? (Seems so, since otherwise chapters isn't defined.)

– chepner
Mar 22 at 15:12





Is the while loop supposed to be inside separate_files? (Seems so, since otherwise chapters isn't defined.)

– chepner
Mar 22 at 15:12













@GPhilo, ok! I will try to remove the while True.

– Natália Resende
Mar 22 at 15:18





@GPhilo, ok! I will try to remove the while True.

– Natália Resende
Mar 22 at 15:18













That's not the only error you have in the code, but you can start from there. As chepner pointed out, chapters is not defined anywhere

– GPhilo
Mar 22 at 15:20





That's not the only error you have in the code, but you can start from there. As chepner pointed out, chapters is not defined anywhere

– GPhilo
Mar 22 at 15:20












2 Answers
2






active

oldest

votes


















2














I think a simpler definition would be



import re
def separate_files ():
pat = re.compile(r"[@introS].[@introEnd@]")

with open('sample.txt') as file:

for i in filter(pat.match, file):
print(i)
inp = input("write text to a file? Y|N: ")
if inp != "Y":
continue

file_name = input("Name of your file: ")
with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to a file".format(i))


Continue the loop as soon as possible in each case, so that the following code doesn't need to be nested more and more deeply. Also, there's no apparent need to read the entire file into memory at once; just match each line against the pattern as it comes up.



You might also consider simply asking for a file name, treating a blank file name as declining to write the line to a file.



for i in filter(pat.match, file):
print(i)
file_name = input("Enter a file name to write to (or leave blank to continue: ")
if not file_name:
continue

with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to ".format(i, file_name)





share|improve this answer

























  • Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

    – Natália Resende
    Mar 22 at 20:50



















0














I can't run your code but I assume if you remove the



while True:


line it should work fine. This will always be executed as there is nothing checked






share|improve this answer























  • yes, I removed it

    – Natália Resende
    Mar 22 at 20:50











Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55302593%2fstop-while-loop-when-the-text-ends%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














I think a simpler definition would be



import re
def separate_files ():
pat = re.compile(r"[@introS].[@introEnd@]")

with open('sample.txt') as file:

for i in filter(pat.match, file):
print(i)
inp = input("write text to a file? Y|N: ")
if inp != "Y":
continue

file_name = input("Name of your file: ")
with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to a file".format(i))


Continue the loop as soon as possible in each case, so that the following code doesn't need to be nested more and more deeply. Also, there's no apparent need to read the entire file into memory at once; just match each line against the pattern as it comes up.



You might also consider simply asking for a file name, treating a blank file name as declining to write the line to a file.



for i in filter(pat.match, file):
print(i)
file_name = input("Enter a file name to write to (or leave blank to continue: ")
if not file_name:
continue

with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to ".format(i, file_name)





share|improve this answer

























  • Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

    – Natália Resende
    Mar 22 at 20:50
















2














I think a simpler definition would be



import re
def separate_files ():
pat = re.compile(r"[@introS].[@introEnd@]")

with open('sample.txt') as file:

for i in filter(pat.match, file):
print(i)
inp = input("write text to a file? Y|N: ")
if inp != "Y":
continue

file_name = input("Name of your file: ")
with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to a file".format(i))


Continue the loop as soon as possible in each case, so that the following code doesn't need to be nested more and more deeply. Also, there's no apparent need to read the entire file into memory at once; just match each line against the pattern as it comes up.



You might also consider simply asking for a file name, treating a blank file name as declining to write the line to a file.



for i in filter(pat.match, file):
print(i)
file_name = input("Enter a file name to write to (or leave blank to continue: ")
if not file_name:
continue

with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to ".format(i, file_name)





share|improve this answer

























  • Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

    – Natália Resende
    Mar 22 at 20:50














2












2








2







I think a simpler definition would be



import re
def separate_files ():
pat = re.compile(r"[@introS].[@introEnd@]")

with open('sample.txt') as file:

for i in filter(pat.match, file):
print(i)
inp = input("write text to a file? Y|N: ")
if inp != "Y":
continue

file_name = input("Name of your file: ")
with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to a file".format(i))


Continue the loop as soon as possible in each case, so that the following code doesn't need to be nested more and more deeply. Also, there's no apparent need to read the entire file into memory at once; just match each line against the pattern as it comes up.



You might also consider simply asking for a file name, treating a blank file name as declining to write the line to a file.



for i in filter(pat.match, file):
print(i)
file_name = input("Enter a file name to write to (or leave blank to continue: ")
if not file_name:
continue

with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to ".format(i, file_name)





share|improve this answer















I think a simpler definition would be



import re
def separate_files ():
pat = re.compile(r"[@introS].[@introEnd@]")

with open('sample.txt') as file:

for i in filter(pat.match, file):
print(i)
inp = input("write text to a file? Y|N: ")
if inp != "Y":
continue

file_name = input("Name of your file: ")
with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to a file".format(i))


Continue the loop as soon as possible in each case, so that the following code doesn't need to be nested more and more deeply. Also, there's no apparent need to read the entire file into memory at once; just match each line against the pattern as it comes up.



You might also consider simply asking for a file name, treating a blank file name as declining to write the line to a file.



for i in filter(pat.match, file):
print(i)
file_name = input("Enter a file name to write to (or leave blank to continue: ")
if not file_name:
continue

with open(file_name, "w") as out_file:
out_file.write(i)
print("text written to ".format(i, file_name)






share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 22 at 15:24

























answered Mar 22 at 15:19









chepnerchepner

264k36255346




264k36255346












  • Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

    – Natália Resende
    Mar 22 at 20:50


















  • Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

    – Natália Resende
    Mar 22 at 20:50

















Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

– Natália Resende
Mar 22 at 20:50






Thank you so much! I was wondering if it is possible to ask the program create the files and give a name to each file automatically instead of asking the user to name a file to created it. Is that possible? If so, could you please show me how do it?

– Natália Resende
Mar 22 at 20:50














0














I can't run your code but I assume if you remove the



while True:


line it should work fine. This will always be executed as there is nothing checked






share|improve this answer























  • yes, I removed it

    – Natália Resende
    Mar 22 at 20:50















0














I can't run your code but I assume if you remove the



while True:


line it should work fine. This will always be executed as there is nothing checked






share|improve this answer























  • yes, I removed it

    – Natália Resende
    Mar 22 at 20:50













0












0








0







I can't run your code but I assume if you remove the



while True:


line it should work fine. This will always be executed as there is nothing checked






share|improve this answer













I can't run your code but I assume if you remove the



while True:


line it should work fine. This will always be executed as there is nothing checked







share|improve this answer












share|improve this answer



share|improve this answer










answered Mar 22 at 15:18









MaxSMaxS

118114




118114












  • yes, I removed it

    – Natália Resende
    Mar 22 at 20:50

















  • yes, I removed it

    – Natália Resende
    Mar 22 at 20:50
















yes, I removed it

– Natália Resende
Mar 22 at 20:50





yes, I removed it

– Natália Resende
Mar 22 at 20:50

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55302593%2fstop-while-loop-when-the-text-ends%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript