GMgKe586q6suSQnyqZLlGCooeWM

Pages

Search

Sunday, May 8, 2011

Python - File Reading And Writing

Introduction

File operation is necessary in every programming.In Python, file handling is comparatively easier than the other language.

Reading A File

For reading a file, you can use open built-in method with or without "r" mode as a second arguments.

Program Code

finput = open("lola.txt")
print finput
data = finput.read()
print data

Output

<open file 'none.txt', mode 'r' at 0x00B34440>
Welcome to Python world. Python is a nice language. It's fun to learn. And it's easy to use.
In the above code, we open file accesss using open built in method and supply its argument with filename. Then we use read method to read all the contents of the file, and save it in variable data.

Writing To A File

For writing to a file, you also use built in open method with the mode "w". For example

Program Code

foutput = open("lola.txt", "w")
foutput.write("Hello From Python.")
foutput.write("We love to do what the best.")
foutput.close()
When you write a file in Python, you need to end your code with close method so the buffer will be flushed.


Share/Bookmark

No comments:

Post a Comment