Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Introduction to File Handling | File Handling
Python Advanced Concepts
course content

Conteúdo do Curso

Python Advanced Concepts

Python Advanced Concepts

1. Modules and Imports
2. Error Handling
3. File Handling
4. Pytest Framework
5. Unittest Framework
6. Iterators and Generators

book
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.

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 3. Capítulo 1
We're sorry to hear that something went wrong. What happened?
some-alt