Read a file in Python

Use the function open() to open the file.

A file object with a method read() is the function open() returns, allowing you to read the contents of the file:

f = open("fichierdemo.txt", "r")
print(f.read())

Read part of the file

The read() returns the full file, you can specify the maximum number of characters to read.

f = open("fichierdemo.txt", "r")
print(f.read(10))

Read a line

A single line can be read using the method readline().

f = open("fichierdemo.txt", "r")
print(f.readline())
In this example the program returns only the first line of the file. If you want to read the second line just add a second time f.readline().

If you want to browse all the lines, here's how:
 
f = open("fichierdemo.txt", "r")
for x in f:
print(x)

Close file

After reading, it is recommended to close the file, just add the statement f.close() at the end of the programme.
Advertisement

AdBlock Detected

Please disable your ad blocker and refresh the window to use this website.