April 19, 2017

Python script for file handling - Read & Write

# Basic File Handling in Python - Read & Write
# coding: utf-8 # for Non-ASCII character support

# Writing to a file
f = open("<file path>/file_read_write.txt", "w");
f.write("Name                    Age                  \n")
f.write("-----------------------------------------\n")

mystring = "%s                   (%d) \n" % ("Ram", 32)
f.write(mystring)

f.close() 

# Reading from a file
f = open("<file path>/file_read_write.txt", "r") 
print f.read() 

f.close()

Note:
you may also try the following commands for selective read(s)
    print f.read(4)
    print f.readline()
    print f.readline(3)

No comments:

Post a Comment