Conteúdo do Curso
Python Advanced Concepts
Python Advanced Concepts
Introduction to File Handling
Files are a crucial medium for long-term storage of data. During program execution, values of variables are stored in memory, which is volatile. To retain information beyond the lifespan of the program, we store data in files. The open()
function is central to file operations in Python, allowing us to create, read, update, and delete files.
Opening Files
To open a file, use the open()
function, which requires at least one argument: the file path. If the file exists, it will be opened; if not, a new file will be created depending on the mode specified:
If a mode is not specified, Python opens the file in the default read ('r') mode.
File Modes
Understanding file modes is crucial for handling files appropriately:
'r'
: open only for **reading **(default). The file pointer is placed at the beginning of the file;'r+'
: open for reading and writing;'w'
: open only for writing. Overwrites the file if it exists or creates a new file;'w+'
: open for writing and reading. Creates a new file if it doesn't exist;'a'
: open for appending. The file pointer is at the end if the file exists. Creates a new file for writing if it does not exist;'a+'
: open for reading and appending;'rb'
,'wb'
,'ab'
,'rb+'
,'wb+'
,'ab+'
: similar modes but for binary files;'x'
: open for exclusive creation, failing if the file already exists;
Example of Opening a File
Note
It's good practice to close the file when done to prevent system errors.
Obrigado pelo seu feedback!