Languages
[Edit]
EN

Python - read file

0 points
Created by:
marc_so
1104

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))
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

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