Python file access modes¶
In Python, file access modes are specific strings passed to the open() function to determine the capabilities permitted on a file object, such as reading, writing, or creating.^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md] These modes define whether a file is opened for modification, whether the file pointer is placed at the beginning or end, and how the system behaves if a file does or does not exist.^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]
Modes Overview¶
The open() function generally accepts at least two arguments: the file path and the mode string.^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]
Read Mode ("r")¶
This is the default mode if no mode is specified^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]. It opens a file for reading only. If the file does not exist at the specified path, the operation raises a FileNotFoundError^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md].
Append Mode ("a")¶
This mode opens a file for appending data^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]. Unlike read mode, if the target file does not exist, append mode will create it automatically^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md].
Write Mode ("w")¶
Write mode opens a file for writing content^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]. Like append mode, it will create a new file if one does not exist^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md].
Create Mode ("x")¶
This mode is strictly used to create a new file^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]. It differs from write and append modes in that it will return an error if the file specified already exists^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md].
Related Concepts¶
- [[Python]]
- [[File Handling]]
- [[CSV]]
Sources¶
^[400-devops__09-Scripting-Language__python__introduction__part-2.files__README.md]