TAILIEUCHUNG - Dive Into Python-Chapter 10. Scripts and Streams

Tham khảo tài liệu 'dive into python-chapter 10. scripts and streams', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Chapter 10. Scripts and Streams . Abstracting input sources One of Python s greatest strengths is its dynamic binding and one powerful use of dynamic binding is the file-like object. Many functions which require an input source could simply take a filename go open the file for reading read it and close it when they re done. But they don t. Instead they take a file-like object. In the simplest case a file-like object is any object with a read method with an optional size parameter which returns a string. When called with no size parameter it reads everything there is to read from the input source and returns all the data as a single string. When called with a size parameter it reads that much from the input source and returns that much data when called again it picks up where it left off and returns the next chunk of data. This is how reading from real files works the difference is that you re not limiting yourself to real files. The input source could be anything a file on disk a web page even a hard-coded string. As long as you pass a file-like object to the function and the function simply calls the object s read method the function can handle any kind of input source without specific code to handle each kind. In case you were wondering how this relates to XML processing is one such function which can take a file-like object. Example . Parsing XML from a file from import minidom fsock open 1 xmldoc fsock 2 3 print 4 xml version- grammar ref id bit p 0 p p 1 p ref ref id byte p xref id bit xref id bit xref id bit xref id bit xref id bit xref id bit xref id bit xref id bit p ref grammar 1 First you open the file on disk. This gives you a file object. 2 You pass the file object to which calls the read method of fsock and reads the XML document from the file on disk. 3 Be sure to call the close method of the file object after you re done with it. will not .

TỪ KHÓA LIÊN QUAN
Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.