Tuesday, July 28, 2015

File Handling Best Practices

File Handling Best Practices:

>>>fp = open('testfl.txt','r+') # Opens a file in read and write mode
>>> fp.read()  # read all contents of the file
'My first line\n'
>>> fp.seek(0) # changes the position of fp to 0
>>> fp.read(1)  # Read one byte from file
'M'
>>> fp.read(2)
'y '
>>> fp.flush()  # Always Best Practice to use flush when changing from read to write operation or from vice versa.

>>> fp.seek(0)
>>> fp.seek(16)
>>> fp.tell()
16L
>>> fp.write('My Second Line\n')
>>> fp.flush()
>>> fp.read()
''
>>> fp.tell()
32L
>>> fp.seek(0)
>>> fp.read()
'My first line\n\x00My Second Line\n'
>>> fp.seek(0)

>>> for line in fp:
print line

My first line

 My Second line

>>> fp.close()   # Always close a file once opened via open function.
>>> fp.closed
True 

# With Open syntax will handle the all the error handling internally and also closes files automatically.
>>> with open('testfl.txt','r+') as fp1:  
fp1.read()


'My first line\n\x00My Second Line\nMy Third Line\n'

>>> with open('testfl.txt','r+') as fp1:  
print fp1.read()


My first line
My Second Line

My Third Line

No comments:

Post a Comment