How do I use while/if loop when creating and writing a txt file on python?
For instance if input string has exit such as [orange, apple, exit, peach] how can I break the loop right before exit? If input is [orange, apple, exit, peach] the outcome I'm expecting in txt file is [orange apple].
Original Question:
Write a note-taking script that keeps asking the user for text and writes it to a file called notes.txt
one line at a time, until the user writes the word exit
alone on a line. This word should not be saved.
Then write, in a separate cell, a script that prints the contents of notes.txt
to the screen.
Note that each time you run the note-taking script file notes.txt
is cleared. To avoid this, modify the script so that it opens the file for appending instead of for writing - simply change the 'w'
into an 'a'
in the open()
statement.
note = str(input('Enter notes:'))
notes = note.split()
# print list
print('list: ', notes)
with open("file path/notes.txt", 'w') as f:
f.write('\n'.join(notes))
f.close()
CodePudding user response:
while True:
note = str(input('Enter notes:'))
if note == 'exit':
break
notes = note.split()
# print list
print('list: ', notes)
with open("file notes.txt", 'a') as f:
f.write('\n'.join(notes))
f.close()
CodePudding user response:
For this question, you can choose one of the below scripts:
#!/usr/bin/python3
while True:
note = input("Enter notes:")
if note == "exit":
break
with open('notes.txt', 'a') as notes_file:
notes_file.write('\n'.join(note))
or
#!/usr/bin/python3
notes_file = open('notes.txt', 'a')
exit_flag = False
while not exit_flag:
note = input("Enter notes:")
if note == "exit":
exit_flag = True
if exit_flag:
notes_file = notes_file.close()
break
notes_file.write('\n'.join(note))
Note: This is a very simple question, but my purpose in answering this question was to pay attention to these few points in writing your python scripts:
When you use
with
context manager, you no longer need toclose()
for your file and it will close that by itself.In the usual case,
input()
type is of string type and you don't need to cast it to string data type, and writingstr()
in your case is extra work. Normally, at this level, any type of data that has been written ininput()
is ofstr
type.