Sunday, August 16, 2015

Python on the go - Revision of Files

One of the simplest ways for programs to maintain their data is by reading and writing
text files.

To write a file, you have to open it with mode 'w' as a second parameter:

file = open('out.txt', 'w')
file.write("Hello there.\n")
file.close()


If the file already exists in the same directory as the program, opening it in write mode clears out the old data . If the file doesn’t exist, a new one is created.


To read a file, you have to open it with mode 'r' as a second parameter:

file = open('out.txt', 'r')
print file.read()


file.read() returns a string with all the characters in the file. With print, the output can be seen in the Python shell.

The above two programs can be combined in one program to write and read a file.


file = open('out.txt', 'w')
file.write("Hello there.\n")
file.close()

file = open('out.txt', 'r')
print file.read()

No comments:

Post a Comment