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

Contenido del Curso

Python Advanced Concepts

Python Advanced Concepts

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

bookReading and Writing Files

Reading from a File

To start reading a file, you first need to open it in the appropriate mode. Here's how you can open and read from a file:

Reading Specific Characters

You can also read a specific number of characters by passing a numeric argument to the read method:

Reading Line by Line

To read a file line by line, you can use a loop along with the readline() or readlines() methods. The readline() method returns a string for each line, while readlines() returns a list of all lines:

For more efficient line-by-line reading without loading the entire file into memory, use a for loop with readlines():

Writing to a File

To write data to a file, you should open it in write mode ('w'). Only strings can be passed to the write() method.

Note

The writing mode overwrites the existing file content.

In this case, any existing data in "greetings.txt" will be replaced with "Bonjour!"

Choose the right statement for the `'r'` mode:

Choose the right statement for the 'r' mode:

Selecciona la respuesta correcta

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 3. Capítulo 2
We're sorry to hear that something went wrong. What happened?
some-alt