Custom Search

Sunday, March 27, 2011

python Simple File Read and Write

python Simple File Read and Write

fp = open("test_file_1", "w")

h1 = "hello1"
h2 = "hello2"
h3 = "hello3"
h4 = "hello4"

fp.write(h1)
#OR
print >> fp, h2, h3
print >> fp, h4
#close file
fp.close()

OUTPUT
======
hello1hello2 hello3
hello4


Note
====
To open a file/file object :

open(filename,mode)

1. filename can be a file or path to a file
2. mode can be any of the following

1. ‘r’ for reading
2. ‘r+’ for reading and writing
3. ‘w’ for writing
4. ‘a’ for appending
5. both read and write modes also have a ‘b’ option for binary reading and writing (‘rb’, or ‘wb’)

s = myFile.read() Will read entire file into a string
s = myFile.read(N) Will read N bytes (1 or more) from file
s = myFile.readline() Will read next line into string until end of line
L = myFile.readlines() Will read entire file into a list of strings

No comments:

Post a Comment