How to read a folder in python

(*-*)浩
Release: 2019-06-20 14:29:46
Original
4887 people have browsed it

Reading files is the most common IO operation. Python has a built-in function for reading files, and its usage is compatible with C.

How to read a folder in python

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')
Copy after login

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'
Copy after login

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!'
Copy after login

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()
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template