Thursday, October 9, 2014

Python Code for File reading

To express the statements we can used the print statement or the write() method of file. Now we will read from file and write that content to file.

 

Reading File

1 fd = open("D:/Research/python/test.log", "r+")
2 print fd.read(4)
3 print fd

Out put

image

 

Write to file


1 fd = open("D:/Research/python/test.txt", "w+")
2 fd.write("This is a test file.\n")
3 fd.close()

fd.readline() reads a single line from the file;


For reading lines from a file, you can loop over the file object. This is memory efficient, fast, and leads to simple code.


1 fd = open("D:/Research/python/test.txt", "r+")
2 print fd.read()
3 for line in fd:
4 print line;

No comments:

Post a Comment