Reading files is the most common IO operation. Python has a built-in function for reading files, and its usage is compatible with C.
Before reading files, we must first understand that the function of reading files on disk is provided by the operating system. Modern operating systems do not allow ordinary programs to operate directly. disk, so to read and write files is to request the operating system to open a file object (often called a file descriptor), and then read data from this file object (read the file) through the interface provided by the operating system. (Recommended learning: Python video tutorial)
Reading files
To open a file object in file reading mode, use Python The built-in open() function passes in the file name and identifier:
>>> f = open('/Users/michael/test.txt', 'r')
The identifier 'r' means read. In this way, we successfully opened a file.
If the file does not exist, the open() function will throw an IOError and give you an error code and detailed information to tell you that the file does not exist:
>>> f=open('/Users/michael/notfound.txt', 'r') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: '/Users/michael/notfound.txt'
If the file is opened successfully, next, call the read() method to read the entire content of the file at once. Python reads the content into the memory and represents it with a str object:
>>> f.read() 'Hello, world!'
The last step is Call the close() method to close the file. The file must be closed after use, because the file object will occupy the resources of the operating system, and the number of files that the operating system can open at the same time is also limited:
>>> f.close()
For more Python-related technical articles, please visit Learn in the Python tutorial column!
The above is the detailed content of How to read a folder in python. For more information, please follow other related articles on the PHP Chinese website!