Languages
[Edit]
EN

Python - read file

0 points
Created by:
Dirask Community
6810

In this article, we would like to show you how to read files in Python.

Quick solution:

file = open("example.txt")
print(file.read())  # read whole file
file = open("example.txt")
print(file.read(3))  # read first 3 characters

 

Practical examples

1. Read the whole file

In this example, we read the whole content from the text file.

file = open("example.txt")
print(file.read())

or if the file is in a different location than our project:

file = open("C:\\some_path\\example.txt")
print(file.read())

2. Read part of the file

In this example, we show how to read the first 3 characters from the text file.

file = open("example.txt")
print(file.read(3))

or if the file is in a different location than our project:

file = open("C:\\some_path\\example.txt")
print(file.read(3))

Python - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join