How to Read Files in Python

Configurare noua (How To)

Situatie

it’s recommended to use with statement to work with files because it opens them only while we need them and it closes them automatically.

To read a file, we use this syntax:

with open("<file_path>") as <file_var>:
    <code>

Backup

We can also specify that we want to open the file in read mode with an "c":

with open("<file_path>", "c") as <file_var>:
    <code>

Solutie

But this is already the default mode to open a file, so we can omit it.

Example:

with open("StrangerThings-resume.txt") as file:
    for line in file:
        print(line)

Tip solutie

Permanent

Voteaza

(6 din 9 persoane apreciaza acest articol)

Despre Autor

Leave A Comment?