File-basic File operation FEB 24TH, 2013 learning a language, I always like to start from a File. Reading and writing text files is a basic function that I care about. In this regard, the Java language has powerful functions and many design patterns are used. It is too cumbersome to use. Python performs very well in this aspect, which is concise, powerful, and elegant, and worthy of praise. Let's start with the simplest one. With open ('/etc/resolv. conf') as f: print (f. read () The with syntax is used to close the file handle. Open () First, let's take a look at the open () built-in functions. Open (file, mode = 'R', buffering =-1, encoding = None, errors = None, newline = None, closefd = True, opener = None) open file and return a corresponding file object. if the file cannot be opened, an OSError is raised. there are many open () parameters. Generally, you need to pay attention to mode, encoding, errors, and newline. Best Practices (1) reading files must pass in character encoding (2) when used up stream needs to be closed, we recommend using the with Operation (3) line breaks as much as possible using UNIX format (\ n ), although python can be intelligently converted (4) If possible, use UTF-8 encoding to process non-ascii characters as much as possible. Do not rely on the operating system encoding tips: You can use the with syntax for simultaneous operations on multiple files: with open ('/etc/hosts', 'R') as f, open ('/tmp/hosts', 'w') as t: // do something or with f = open ('/etc/hosts'), t = open ('/tmp/hosts', 'w '): // The do something file object describes a "stream" operation. Generally, the read () or write () method is supported. The object here is a conceptual "file object". In addition to common real disk files, it can also be a standard input/output file (stdin/stdout/stderr ), memory buffer (StringIO, cStringIO), socket, pipes, etc. This is described in the io module. There are some differences between text operations and binary operations. Introduction. Text I/O if the mode contains t (default), the returned stream is a plain Text operation. Read () is the simplest way to read text. The returned result is a string (related to the encoding parameter ). Read (n) Read and return at most n characters from the stream as a single str. if n is negative or None, reads until EOF. in many installation scripts, readme = open ('. /README. md '). read () is similar. This is not a problem in a fast-ending program. In the official service, you should close the file handle at any time to release resources. Tip: if you have read to the end of the file, read () returns an empty string ''. To read a row, use the readline () method. Readline (limit =-1) Read until newline or EOF and return a single str. if the stream is already at EOF, an empty string is returned. if limit is specified, at most limit characters will be read. reading a row is related to the row Terminator, which is a bit complicated. Read multiple rows and use the readlines () method. This returns a string list. Readlines () can also limit the maximum number of characters to read. Tip: readline (limit =-1) and readlines (limit =-1) have different limit descriptions. Readline (limit =-1) describes how to read a row. A maximum of limit characters (not bytes) are allowed. Therefore, the result may not end with a row. Readlines (limit =-1) describes the read characters until the end of the row where the limit characters are located. That is, the returned result must end with a certain row (unless EOF ). For example, >>> open ('/tmp/x1', 'w '). write ('python is really a good student. \ n is only limited to two versions. \ n I support python3.x') 40 >>> open ('/tmp/x1 ', 'R '). readline (10) 'python is really a '>>> open ('/tmp/x1', 'R '). readlines (10) ['python is really a good student \ n'] readlines (limit) is an incomprehensible logic. If possible, do not transmit any parameter. Refer to here. You can use the write (s) method to write text: Write (s) write the string s to the stream and return the number of characters written. the string is written, not the byte. To Write multi-line strings, you can use the writelines (lines) method. TIPS: write (s) and writelines (lines) do not write the row terminator into the file stream. Therefore, you must manually write the row Terminator. The Binary I/O Binary stream is similar to the text stream, but the Binary stream has no encoding. To open a binary stream, you must input the 'B' parameter in the mode parameter '. For example, >>> type (open ('/etc/hosts', 'rb '). read () <class 'bytes '> compared with text streams, binary streams have some minor differences: the value returned by read () is byte (bytes) readline () the returned value is bytes, including the value returned by the linefeed readlines () is the bytes list, including the line feed write () parameter which can be bytes or bytearrayreadinto (B) is to read the content to bytearray B, returns the number of bytes read. In addition to the read/write method, other file operations include file. close () close file. fileno () obtains the file descriptor (integer value) file. flush () refreshes the buffer file for write operations with a buffer. tell () returns the byte location file of the current stream. seek () moves the current location of the file stream file. truncate () truncated File Size