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

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현