How to read a file in Python
To open and read a file using the Python language
- Open the file with the open() statement and the r (read) attribute. The method assigns the file to an object (variable) of the program.
f = open('nomefile.txt', 'r')
- Read one record at a time using the readline() method.
record = f.readline()
- When finished, close access to the file using the close() method.
f.close()
This allows other programs to access the file.
Examples
Example 1
This script opens and reads the first three records of a file.
f = open("nomefile","r")
print(f.readline())
print(f.readline())
print(f.readline())
f.close()
https://how.okpedia.org/en/python/how-to-read-a-file-in-python
Report an error or share a suggestion to enhance this page