Skip to content

Instantly share code, notes, and snippets.

@vijayanandrp
Created June 15, 2017 21:38
Show Gist options
  • Save vijayanandrp/7a5894b034ee77494abf9c1818b0c1f4 to your computer and use it in GitHub Desktop.
Save vijayanandrp/7a5894b034ee77494abf9c1818b0c1f4 to your computer and use it in GitHub Desktop.
Learn file concepts in python - Read time - 5 mins!!
#!/usr/bin/env python
# Just for practicing the file operation in python
def file_basics():
print ' File Operations\n', '*' * 80
types_of_file = """
Text Files represent content as normal str strings, perform unicode and decoding automatically (plain)
Examples: .txt is a plain file
Binary Files represent content as special bytes string type and allows program to access the content unaltered \n
Example: .wav, .exe, .mp3 all are binary files
(Python handles both 8-bit text and binary data and a special string type)
"""
print types_of_file
# Handling Text Files
# Writing the content to a new file
myfile = open('myfile.txt', 'w')
myfile.write('hello text file \n')
myfile.write(types_of_file)
myfile.write('\n good bye, sweet dreams :P sleep tight \n')
myfile.flush() # Writes the content from the buffer (OS) to the disc
myfile.close()
print '- - ' * 25
# Reading the Content from the file
myfile = open('myfile.txt', 'r') # Default 'r' read mode only
print myfile.readline()
print myfile.readline() # Reading line by line
print myfile.readline()
myfile.close()
print '- - ' * 25
# Reading all at once
content = open('myfile.txt').read()
print content.rstrip()
print '= = ' * 25
# Reading the file content using the iterator
for line in open('myfile.txt'):
print line
print '= = ' * 25
print r'c:\Python33\Lib\pdb.py' # Raw String as a input
# Handling Binary Files
with open('data.bin', 'wb') as bin_file:
bin_file.write('\\x00\\x00\\x00\\x07spam\\x00\\x08')
data = open('data.bin', 'rb').read()
print "Binary data = ", data
print eval('[1, 2, 4]') # eval() converts the string into any object type
def lib_pickle():
print "\n Pickle is used to dump the any objects into a file \n", '_' * 80
F = open('datafile.pk1', 'wb')
D = {'a': 1, 'b': 2}
import pickle
pickle.dump(D,F)
F.close()
F = open('datafile.pk1', 'rb')
E = pickle.load(F)
print E
F.close()
print "\n actual dump is ", open('datafile.pk1', 'rb').read()
F.close()
def lib_struct():
print "\n struct is used to pack and unpack the binary files \n", '_' * 80
print 'Writing the Data'
F = open('data.bin', 'wb')
import struct
data = struct.pack('>i4sh', 7, b'spam', 8)
print data
F.write(data)
F.close()
print "\n Reading the data"
F = open('data.bin', 'rb')
data = F.read()
print data
values = struct.unpack('>i4sh', data)
print values
F.close()
def main():
file_basics()
lib_pickle()
lib_struct()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment