[source code] Python Programming Tutorial - 23 - How to Read and Write Files

+2 Bucky Roberts · September 2, 2014
I read in the comments that a lot of people were having trouble reading the text on the screen, so I increased the font size in this tutorial. Let me know how it looks!
fw = open('sample.txt', 'w')
fw.write('Writing some stuff in my text file\n')
fw.write('I like bacon\n')
fw.close()

fr = open('sample.txt', 'r')
text = fr.read()
print(text)
fr.close()

Post a Reply

Replies

Oldest  Newest  Rating
+1 Doug Fresh · November 24, 2014
You have 2 possible solutions. You can either open the data and store it in a variable, append the new info, then write the appended variable to the file. Or you can use the append modifier from the open function seen below:
## note instead of open('sample.txt', 'w') the 'r' is replaced with an 'a'

fw = open('sample.txt', 'a')
fw.write("\n Writing some new stuff here, without erasing the old stuff \n")
fw.write("#bacon")
fw.close()

## now we'll open it and seem what it says
fr = open('sample.txt', 'r')
text = fr.read()
print(text)
fr.close()
0 Anindya Moitra · November 24, 2014
Hey! The font looks perfect.
I was wondering how we could append texts to a file that was already created and already had stuff written in it.
  • 1

Python

107,350 followers
About

This section is all about snakes! Just kidding.

Links
Moderators
Bucky Roberts Administrator