Python File I/O

Indroduction of File System

A file in python usually categorized as either text or binary,a text file is often structured as a sequence of line and a line is a sequence of characters.the line is terminated by a EOF character.

The most common line end with ',' or the newline character.the backslash character indicates that the next character will be treated as a newline.

Open()

The open a file for writing use the buil-i open() function.open() return a file object,and is most commonly used with two arguments.

Syntax

							
file_object = open(filename,mode)
							
							

Mode

The mode arguments is optional,the modes can be:

      'r' - when the file will only be read.

      'w' - for only writing.

      'a' - Open the file for appending.

      'r+' - open the file for both reading and writing.

							
f = open('testfile.txt','w');
							
							

How to Create a text File

In python create a text file first create a text file,you can name it anything you like following example.

							
f = open('testfile.txt','w');
							
							

How to Write a Text File

The write method takes one parameter,which is the string to be written.

							
file = open("test.txt","w");

file.write("Welcome");

file.close();
							
							

How to Read a Text File

In python read a file the following example of read file in python.

							
file = open('text.txt'.'r');

print file.read();

file.close();
							
							

Close()

When you are done with a file,call file.close() to close it and free up any system resources taken up by the open file.

Share Share on Facebook Share on Twitter Share on Google+ Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit