预计阅读本页时间:-
Opening Files
To open a file, a program calls the built-in open function, with the external filename first, followed by a processing mode. The mode is typically the string 'r' to open for text input (the default), 'w' to create and open for text output, or 'a' to open for appending text to the end. The processing mode argument can specify additional options:
广告:个人专属 VPN,独立 IP,无限流量,多机房切换,还可以屏蔽广告和恶意软件,每月最低仅 5 美元
- Adding a b to the mode string allows for binary data (end-of-line translations and 3.0 Unicode encodings are turned off).
- Adding a + opens the file for both input and output (i.e., you can both read and write to the same file object, often in conjunction with seek operations to reposition in the file).
Both arguments to open must be Python strings, and an optional third argument can be used to control output buffering—passing a zero means that output is unbuffered (it is transferred to the external file immediately on a write method call). The external filename argument may include a platform-specific and absolute or relative directory path prefix; without a directory path, the file is assumed to exist in the current working directory (i.e., where the script runs). We’ll cover file fundamentals and explore some basic examples here, but we won’t go into all file-processing mode options; as usual, consult the Python library manual for additional details.