0% found this document useful (0 votes)
2 views

P8-Iterator

The document covers various Python programming concepts including generators, iterators, and closures, as well as file handling and operations using the Python Standard Library modules such as os, datetime, time, and calendar. It explains the functionality of iterators and generators, file streams, and methods for reading and writing files. Additionally, it provides examples of using lambda functions and various methods from the os and datetime modules.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

P8-Iterator

The document covers various Python programming concepts including generators, iterators, and closures, as well as file handling and operations using the Python Standard Library modules such as os, datetime, time, and calendar. It explains the functionality of iterators and generators, file streams, and methods for reading and writing files. Additionally, it provides examples of using lambda functions and various methods from the os and datetime modules.

Uploaded by

s112701018.mg12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

PE2 Module 4

 Miscellaneous
 Generators, iterators and closures;

 Working with file-system, directory tree and files;

 Selected Python Standard Library modules (os, datetime,

time, and calendar).

廖文宏 Python Programming 1


4.1.1 Generator/Iterator
 generator is a piece of specialized code able to produce a
series of values, and to control the iteration process.
 generators are very often called iterators

 e.g. range()
range(5) generator is invoked six times, providing five
subsequent values from zero to four, and finally signaling
that the series is complete.

廖文宏 Python Programming 2


4.1.1 Iterator
 An iterator is an object that contains a countable number of
values that can be iterated.
 Lists, tuples, dictionaries, and sets are all iterable
objects. You can get iterator from these objects by iter()
 e.g. fruit = iter(["apple", "banana", "cherry"])

print(next(fruit)) # apple
print(next(fruit)) # banana

 ps: The for loop actually creates an iterator object and


executes the next() method for each loop.
廖文宏 Python Programming 3
4.1.1.2 Iterator
 An iterator must provide two methods:
 __iter__() : return the object itself and which is invoked

once
 __next__() : return the next value, if there are no more

values to provide, the method should raise the


StopIteration exception.

廖文宏 Python Programming 4


Example: Counter
 e.g.
class myCounter:
def __iter__(self):
self.i = 1
return self
def __next__(self):
ret = self.i
self.i += 1
return ret
c = iter(myCounter())
print(next(c))
print(next(c))
廖文宏 Python Programming 5
廖文宏 Python Programming 6
4.1.1.4 yield
 The iterator main discomfort is the need to save the state of
the iteration between subsequent __iter__ invocations.
 yield: more effective, convenient way of writing iterators.
 e.g.

such a function should not be invoked explicitly. it isn't a function anymore; it's a generator object.
廖文宏 Python Programming 7
4.1.1.9 lambda function
 A lambda function is a function without a name
(anonymous function).
 syntax
lambda parameters : expression
 returns the value of the expression

 e.g.
sqr = lambda x : x*x
sqr(3)
 e.g.
max = lambda a, b: a if a > b else b
maximum = max(10,20)
 lambda function and map(), filter()
廖文宏 Python Programming 8
4.2.1 Processing Files
 File Stream
 Program does not communicate with the files directly,

but through some abstract entities - the most-used terms


are handle or stream.
 The operation of connecting the stream with a file is

called opening the file, while disconnecting this link is


named closing the file.
 detect opening error
 4.2.1.6 text stream versus binary stream

廖文宏 Python Programming 9


4.2.1 File Stream
 The stream behaves almost
like a tape recorder.

 When you read something from a stream, a virtual head


moves over the stream according to the number of bytes
transferred from the stream.
 When you write something to the stream, the same head
moves along the stream recording the data from the
memory.
廖文宏 Python Programming 10
4.2.1.4 File Stream Modes
 read mode: allows read operations only
 trying to write to the stream will cause an exception (the

exception is named UnsupportedOperation, which


inherits OSError and ValueError, and comes from the io
module);
 write mode: allows write operations only
 attempting to read the stream will cause the exception

mentioned above;
 update mode: allows both writes and reads.

廖文宏 Python Programming 11


4.2.1.5 File Object
 every file is hidden behind an object of an adequate class.

廖文宏 Python Programming 12


4.2.1.7 open()
 syntax: open(filename, mode, encoding)
 e.g. file = open('C:/home/data.txt', 'r+', encoding='UTF-8')

 file open mode

廖文宏 Python Programming 13


4.2.1.9 Pre-opened streams
 sys.stdin
 standard input (normally associated with the keyboard)

 input() function reads data from stdin by default

 sys.stdout
 standard output (normally associated with the screen)

 print() function outputs the data to the stdout stream

 sys.stderr
 standard error output

廖文宏 Python Programming 14


4.2.1.10 File Stream Error Number
 errno.EACCES → Permission denied
 errno.EBADF → Bad file number
 errno.EEXIST → File exists
 errno.EFBIG → File too large
 errno.EMFILE → Too many open files
 errno.ENOENT → No such file or directory
 errno.ENOSPC → No space left on device
 …

廖文宏 Python Programming 15


4.3.1.3 File Read
 .read()
 read a desired number of characters from the file, and

return them as a string


 .readline()
 read a complete line of text from the text file

 .readlines()
 read all the file contents, and returns a list of strings, one

element per file line.


 the text stream is an instance of the iterable class.
 example 4.3.1.6

廖文宏 Python Programming 16


4.3.1.7 File Write
 .write()
 No newline character is added to the write(), so you have

to add it yourself

廖文宏 Python Programming 17


4.3.1.9 bytearray()
 bytearray(n)
 creates a bytearray object to store n bytes,

e.g. bytearray(10)
 bytearray constructor fills the whole array with zeros

 each bytearray element is integer value

 read() versus readinto()


 object of read() return is immutable

 bytearray() object of readinto() return is mutable

廖文宏 Python Programming 18


4.4 os module
 .uname() (note: Unix only)
 systemname - stores the name of the operating system;

 nodename - stores the machine name on the network;

 release - stores the operating system release;

 version - stores the operating system version;

 machine - stores the hardware identifier, e.g., x86_64.

廖文宏 Python Programming 19


4.4 os module
 .listdir() - list directory
 .mkdir(), .rmdir() - make/remove directory
 .makedirs(), .removedirs() - recursive directory creation/rm
 .chdir() - change directory
 .getcwd() - get current working directory
 .system() - executes a command

廖文宏 Python Programming 20


4.5 date module (from datetime)
 date() - create date object
 .today()
 .fromisoformat('2022-05-05')
 .fromtimestamp() - create a date object from a timestamp
 data class
 .year .month .day

 .replace() .weekday()

廖文宏 Python Programming 21


4.5 time module (from datetime)
 time(hour, minute, second) - create a time object
 .time() - get timestamp
 time object
 .hour .minute .second .microsecond

廖文宏 Python Programming 22


4.5.1.9 built-in time module
 .sleep(), e.g.
import time
time.sleep(seconds)
 .ctime() - converts the time in seconds since January 1,
1970 (Unix epoch) to a string.
 .gmtime()
 .localtime()
 .asctime()
 .mktime()

廖文宏 Python Programming 23


4.6 calendar module
 import calendar
print(calendar.calendar(2022))

廖文宏 Python Programming 24

You might also like