Example of how to read a simple text file in python:
Read a text file
Let's consider the following file iso_8859-1.txt. To read and close the file do:
f = open('iso_8859-1.txt', 'r')
f.closed
Get all the file content
To get all the file content a solution is to use f.read():
f = open('iso_8859-1.txt', 'r')
data = f.read()
f.close
and print the content using
print(data)
returns here:
The following are the graphical (non-control) characters defined by
ISO 8859-1 (1987). Descriptions in words aren't all that helpful,
but they're the best we can do in text. A graphics file illustrating
the character set should be available from the same archive as this
file.
Hex Description Hex Description
20 SPACE
21 EXCLAMATION MARK A1 INVERTED EXCLAMATION MARK
22 QUOTATION MARK A2 CENT SIGN
...
...
...
...
Print line and their index
To go through the content line by line and get the line's index just use splitlines():
lines = data.splitlines()
for idx,line in enumerate(lines):
print(idx,line)
returns
0 The following are the graphical (non-control) characters defined by
1 ISO 8859-1 (1987). Descriptions in words aren't all that helpful,
2 but they're the best we can do in text. A graphics file illustrating
3 the character set should be available from the same archive as this
4 file.
5
6 Hex Description Hex Description
7
8 20 SPACE
9 21 EXCLAMATION MARK A1 INVERTED EXCLAMATION MARK
10 22 QUOTATION MARK A2 CENT SIGN
11 23 NUMBER SIGN A3 POUND SIGN
...
...
...
...
Read a file line by line
Another method using "readline()":
print( 'line 1: ', f.readline() )
print( 'line 2: ', f.readline() )
print( 'line 3: ', f.readline() )
Note: each just readline is used, it goes to the following line. To go back at the beginning of the file a solution is to use seek():
f.seek(0)
To get the number of line, a solution is to use a simple for loop:
NumberOfLine = 0
for line in f:
print( line )
NumberOfLine += 1
Read a data file
To read a data file there are multiples solutions:
- How to read a csv file using pandas in python ?
- How to read a microsoft excel file using python ?
- How to read a JSON file using python ?
References
Links | Site |
---|---|
Page sur le site de python: "Input and Output" | python doc |
How to get line count cheaply in Python? | stackoverflow |
C'est quoi le ascii ? | wikipedia |