FILE I/O 2-BINARY, CSV

 PATHS:

import os 

path=os.getcwd()

The above function gives the current working directory to the var 'path'

To write absolute path either use / or \\ between directories and file names

Writing r before a string opening “ treats all the \ as backslash and not as escape sequence

Standard File Streams

These are file object which get automatically connected to input/output devices for performing action through them

import sys

Streams:

sys.stdin- when reads from standard input

sys.stdout- by default gets printed to screen and output can be put to a file

sys.stderr- similar to stdout but also prints error msg , exceptions and debugging

Methods:

read()-for reading a byte at a time

write(data)-writing data of a console(output device== monitor)

Syntax : sys.stream.method - eg sys.stdout.write(“Hello world”)

CSV- Comma Separated Values

eg: 

import csv

1.) Reading csv file:

f=open("file name","r")

data_table=csv.reader(f)

here data_table is a sequence of lists in which contains each row data is stored separate elements in a list

data_table.line_num is a method which returns the no of rows iterated

2.) Writing csv file

csv_w= csv.writer(f,delimiter=",")

# we are defining an object named csv_w to class writer which has a method writerow [maybe]

csv_w.writerow(data)

csv_w.writerows(collection/sequence of data) 

here data is a list of values of a row


PICKLE - BINARY FILES

File extension - .dat

Pickling is also called serialisation and unpicking is called deserialisation

Serialisation- process of transforming data or object from ram to stream of byte called byte stream before writing it to a file. It can also be called as deflating the data. 

# ML - needs flattened data (if not clear see list flattening)

import pickle

my_dict={'key1':10,"key2":2}

# pickle_file=open("pickle_file.dat","wb") 

# pickle.dump(my_dict,pickle_file)

pickle_file2=open("pickle_file.dat","rb")

new_dict=pickle.load(pickle_file2)

Note :load reads line by line and cannot be iterated through so to access multiple lines we need to use load in try block and in EOFError except block we need to write pass. 

Also the type of data load for file is same as that of dump ie list, tuple or dict

print(new_dict)

# pickling store data in bytes .Good for ML


Comments

Popular posts from this blog

Dictionary and Sets in Python

Insertion Sort in python

Grid Printing Code for Python