Here is simple text file example for beginners, using try..except for reading old content as it may not yet exist.
Adding lines of text to file that may not exist
def lines_to_file(fn='myfile.txt'):
try:
with open(fn) as my_file:
content = my_file.read()
except IOError:
content = ''
while True:
print('''
Content:
-------------------------------------
%s
-------------------------------------
Want to:
1) add a line
2) write and quit
3) quit and ignore changes
''' % content)
response = raw_input()
if response in list('123'):
if response == '1':
new_line = raw_input('Enter new line:\n')
content += new_line + '\n'
elif response == '2':
with open(fn, 'w') as my_file:
my_file.write(content)
break
else:
break
print('Bye, bye!')
lines_to_file()
David W 131 Practically a Posting Shark
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
David W 131 Practically a Posting Shark
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
David W 131 Practically a Posting Shark
TrustyTony 888 ex-Moderator Team Colleague Featured Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.