file object = open(file_name [, access_mode][, buffering])
Modes:
r read
r+ read,write
rb read binary
rw read,write
w write
w+ write,read
wb write binary
a append
a+ append,read
---------------------------------
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
--------------------------------------
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
---------------------------------
There are two important sources, which provide a wide range of utility methods to handle and manipulate files and directories on Windows and Unix operating systems. They are as follows:
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
1. file.close() Close the file.
A closed file cannot be read or written any more.
2 file.flush() Flush the internal buffer, like stdio's fflush.
3 file.fileno() Returns the integer file descriptor that is used by the underlying implementation to request I/O operations
from the operating system.
4 file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
5 file.next() Returnss the next line from the file each time it is being called.
6 file.read([size]) Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
7 file.readline([size]) Reads one entire line from the file.
A trailing newline character is kept in the string.
8 file.readlines([sizehint]) Reads until EOF using readline() and return a list containing the lines.
9 file.seek(offset[,whence]) Sets the file's current position.
10 file.tell() Returns the file's current position
11 file.truncate([size]) Truncates the file's size.
If the optional size argument is present, the file is truncated to (at most) that size.
12 file.write(str) Writes a string to the file. There is no return value.
13 file.writelines
>>> os.getcwd()
'C:\\Python27'
>>> os.path.abspath("bdps.txt")
'C:\\Python27\\bdps.txt'
>>> os.path.isdir("prog")
True
>>> os.listdir(cwd)
>>> os.listdir('c:\\Python27')
----------------------------------------------------------------------------------
Syntax
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
----------------------------------------------------------------------
You need to read or write text data, possibly in different text encodings such as ASCII, UTF-8, or
UTF-16.
with open('somefile.txt', 'rt') as f:
data = f.read()
-------------------------------------------------------------------------------
By default, files are read/written using the system default text encoding, as can be found in
sys.getdefaultencoding(). On most machines, this is set to utf-8. If you know that the text you are
reading or writing is in a different encoding, supply the optional encoding parameter to open().
binary data:
>>> import array
>>> nums=array.array('i',[1,2,3,4])
>>> with open('data.bin','wb') as f:
f.write(nums)
The gzip and bz2 modules make it easy to work with such files. Both modules provide an alternative
implementation of open() that can be used for this purpose.
# gzip compression
import gzip
with gzip.open('somefile.gz', 'rt') as f:
text = f.read()
# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()
Use the os.listdir() function to obtain a list of files in a directory:
import os
names = os.listdir('somedir')
pyfiles = [name for name in os.listdir('somedir') if name.endswith('.py')]
import glob
pyfiles = glob.glob('somedir/*.py')
-----------------------------------------------------------------------------
You want to read and write data over a serial port, typically to interact with some kind of hardware
device (e.g., a robot or sensor).
serial communication is to use the pySerial package.
Getting started with the package is very easy.
You simply open up a serial port using code like this:
import serial
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
baudrate=9600,
bytesize=8,
parity='N',
stopbits=1)
The device name will vary according to the kind of device and operating system. For instance, on
Windows, you can use a device of 0, 1, and so on, to open up the communication ports such as
“COM0” and “COM1.” Once open, you can read and write data using read(), readline(), and write()
calls.
-------------------------------------
You need to serialize a Python object into a byte stream so that you can do things such as save it to a
file, store it in a database, or transmit it over a network connection.
-----------------------------------------------------
>>> import pickle
>>> data={'sno':1,'sname':"ww"}
>>> f=open('dump2','wb')
>>> pickle.dump(data,f)
>>> s=pickle.dumps(data)
>>> f=open('dump2','rb')
>>> data=pickle.load(f)
>>> print data
{'sno': 1, 'sname': 'ww'}
>>> data=pickle.loads(s)
>>> print data
{'sno': 1, 'sname': 'ww'}
-------------------------------------------------------------
>>> import pickle
>>> f = open('somedata', 'wb')
>>> pickle.dump([1, 2, 3, 4], f)
>>> pickle.dump('hello', f)
>>> pickle.dump({'Apple', 'Pear', 'Banana'}, f)
>>> f.close()
>>> f = open('somedata', 'rb')
>>> pickle.load(f)
[1, 2, 3, 4]
>>> pickle.load(f)
'hello'
>>> pickle.load(f)
{'Apple', 'Pear', 'Banana'}
>>>
--------------------------------------------------------
process csv data::
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.reader(f)
headers=next(f1)
for row in f1:
print row
---------------------------------------------------------
-----------------------
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.DictReader(f)
for row in f1:
print row
------------------------------------------------
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks.csv','w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
--------------------------------------------------
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
]
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
--------------------------------------------------------------
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
------------------------------------------------
with open('data.json', 'w') as f:
json.dump(data, f)
---------------------------------------
with open('data.json', 'r') as f:
data = json.load(f)
----------------------------------------------------------
>>> from urllib.request import urlopen
>>> import json
>>> u = urlopen('http://search.twitter.com/search.json?q=python&rpp=5')
>>> resp = json.loads(u.read().decode('utf-8'))
>>> from pprint import pprint
>>> pprint(resp)
---------------------------------------------------
>>> s = '{"name": "ACME", "shares": 50, "price": 490.1}'
>>> from collections import OrderedDict
>>> data = json.loads(s, object_pairs_hook=OrderedDict)
>>> data
OrderedDict([('name', 'ACME'), ('shares', 50), ('price', 490.1)])
-------------------------------------------------------
xml data::
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title)
print(date)
print(link)
print()
Modes:
r read
r+ read,write
rb read binary
rw read,write
w write
w+ write,read
wb write binary
a append
a+ append,read
---------------------------------
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()
--------------------------------------
fo = open("foo.txt", "r+")
str = fo.read(10);
print "Read String is : ", str
# Close opend file
fo.close()
---------------------------------
There are two important sources, which provide a wide range of utility methods to handle and manipulate files and directories on Windows and Unix operating systems. They are as follows:
File Object Methods: The file object provides functions to manipulate files.
OS Object Methods: This provides methods to process files as well as directories.
1. file.close() Close the file.
A closed file cannot be read or written any more.
2 file.flush() Flush the internal buffer, like stdio's fflush.
3 file.fileno() Returns the integer file descriptor that is used by the underlying implementation to request I/O operations
from the operating system.
4 file.isatty() Returns True if the file is connected to a tty(-like) device, else False.
5 file.next() Returnss the next line from the file each time it is being called.
6 file.read([size]) Reads at most size bytes from the file (less if the read hits EOF before obtaining size bytes).
7 file.readline([size]) Reads one entire line from the file.
A trailing newline character is kept in the string.
8 file.readlines([sizehint]) Reads until EOF using readline() and return a list containing the lines.
9 file.seek(offset[,whence]) Sets the file's current position.
10 file.tell() Returns the file's current position
11 file.truncate([size]) Truncates the file's size.
If the optional size argument is present, the file is truncated to (at most) that size.
12 file.write(str) Writes a string to the file. There is no return value.
13 file.writelines
>>> os.getcwd()
'C:\\Python27'
>>> os.path.abspath("bdps.txt")
'C:\\Python27\\bdps.txt'
>>> os.path.isdir("prog")
True
>>> os.listdir(cwd)
>>> os.listdir('c:\\Python27')
----------------------------------------------------------------------------------
Syntax
Here is simple syntax of try....except...else blocks:
try:
You do your operations here;
......................
except ExceptionI:
If there is ExceptionI, then execute this block.
except ExceptionII:
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.
----------------------------------------------------------------------
You need to read or write text data, possibly in different text encodings such as ASCII, UTF-8, or
UTF-16.
with open('somefile.txt', 'rt') as f:
data = f.read()
-------------------------------------------------------------------------------
By default, files are read/written using the system default text encoding, as can be found in
sys.getdefaultencoding(). On most machines, this is set to utf-8. If you know that the text you are
reading or writing is in a different encoding, supply the optional encoding parameter to open().
binary data:
>>> import array
>>> nums=array.array('i',[1,2,3,4])
>>> with open('data.bin','wb') as f:
f.write(nums)
The gzip and bz2 modules make it easy to work with such files. Both modules provide an alternative
implementation of open() that can be used for this purpose.
# gzip compression
import gzip
with gzip.open('somefile.gz', 'rt') as f:
text = f.read()
# bz2 compression
import bz2
with bz2.open('somefile.bz2', 'rt') as f:
text = f.read()
Use the os.listdir() function to obtain a list of files in a directory:
import os
names = os.listdir('somedir')
pyfiles = [name for name in os.listdir('somedir') if name.endswith('.py')]
import glob
pyfiles = glob.glob('somedir/*.py')
-----------------------------------------------------------------------------
You want to read and write data over a serial port, typically to interact with some kind of hardware
device (e.g., a robot or sensor).
serial communication is to use the pySerial package.
Getting started with the package is very easy.
You simply open up a serial port using code like this:
import serial
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
baudrate=9600,
bytesize=8,
parity='N',
stopbits=1)
The device name will vary according to the kind of device and operating system. For instance, on
Windows, you can use a device of 0, 1, and so on, to open up the communication ports such as
“COM0” and “COM1.” Once open, you can read and write data using read(), readline(), and write()
calls.
-------------------------------------
You need to serialize a Python object into a byte stream so that you can do things such as save it to a
file, store it in a database, or transmit it over a network connection.
-----------------------------------------------------
>>> import pickle
>>> data={'sno':1,'sname':"ww"}
>>> f=open('dump2','wb')
>>> pickle.dump(data,f)
>>> s=pickle.dumps(data)
>>> f=open('dump2','rb')
>>> data=pickle.load(f)
>>> print data
{'sno': 1, 'sname': 'ww'}
>>> data=pickle.loads(s)
>>> print data
{'sno': 1, 'sname': 'ww'}
-------------------------------------------------------------
>>> import pickle
>>> f = open('somedata', 'wb')
>>> pickle.dump([1, 2, 3, 4], f)
>>> pickle.dump('hello', f)
>>> pickle.dump({'Apple', 'Pear', 'Banana'}, f)
>>> f.close()
>>> f = open('somedata', 'rb')
>>> pickle.load(f)
[1, 2, 3, 4]
>>> pickle.load(f)
'hello'
>>> pickle.load(f)
{'Apple', 'Pear', 'Banana'}
>>>
--------------------------------------------------------
process csv data::
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.reader(f)
headers=next(f1)
for row in f1:
print row
---------------------------------------------------------
-----------------------
>>> import csv
>>> with open('stocks.csv') as f:
f1=csv.DictReader(f)
for row in f1:
print row
------------------------------------------------
headers = ['Symbol','Price','Date','Time','Change','Volume']
rows = [('AA', 39.48, '6/11/2007', '9:36am', -0.18, 181800),
('AIG', 71.38, '6/11/2007', '9:36am', -0.15, 195500),
('AXP', 62.58, '6/11/2007', '9:36am', -0.46, 935000),
]
with open('stocks.csv','w') as f:
f_csv = csv.writer(f)
f_csv.writerow(headers)
f_csv.writerows(rows)
--------------------------------------------------
headers = ['Symbol', 'Price', 'Date', 'Time', 'Change', 'Volume']
rows = [{'Symbol':'AA', 'Price':39.48, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.18, 'Volume':181800},
{'Symbol':'AIG', 'Price': 71.38, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.15, 'Volume': 195500},
{'Symbol':'AXP', 'Price': 62.58, 'Date':'6/11/2007',
'Time':'9:36am', 'Change':-0.46, 'Volume': 935000},
]
with open('stocks.csv','w') as f:
f_csv = csv.DictWriter(f, headers)
f_csv.writeheader()
f_csv.writerows(rows)
--------------------------------------------------------------
import json
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
------------------------------------------------
with open('data.json', 'w') as f:
json.dump(data, f)
---------------------------------------
with open('data.json', 'r') as f:
data = json.load(f)
----------------------------------------------------------
>>> from urllib.request import urlopen
>>> import json
>>> u = urlopen('http://search.twitter.com/search.json?q=python&rpp=5')
>>> resp = json.loads(u.read().decode('utf-8'))
>>> from pprint import pprint
>>> pprint(resp)
---------------------------------------------------
>>> s = '{"name": "ACME", "shares": 50, "price": 490.1}'
>>> from collections import OrderedDict
>>> data = json.loads(s, object_pairs_hook=OrderedDict)
>>> data
OrderedDict([('name', 'ACME'), ('shares', 50), ('price', 490.1)])
-------------------------------------------------------
xml data::
u = urlopen('http://planet.python.org/rss20.xml')
doc = parse(u)
# Extract and output tags of interest
for item in doc.iterfind('channel/item'):
title = item.findtext('title')
date = item.findtext('pubDate')
link = item.findtext('link')
print(title)
print(date)
print(link)
print()
No comments:
Post a Comment