import mermaid from 'https://cdnjs.cloudflare.com/ajax/libs/mermaid/10.2.3/mermaid.esm.min.mjs'; mermaid.initialize({ startOnLoad: true });
Voici l'exemple :
texte = """
"Libellé","Produit","Prix","Quantite"
"L123","meuble","1000","1"
"L321","portable","500","2"
"L333","lampe","100","4"
"""
with open("exemple_fichier.txt", "w", encoding="utf8") as f:
f.write(texte)
import pandas
df = pandas.read_csv("exemple_fichier.txt", encoding="utf8")
df
Libellé | Produit | Prix | Quantite | |
---|---|---|---|---|
0 | L123 | meuble | 1000 | 1 |
1 | L321 | portable | 500 | 2 |
2 | L333 | lampe | 100 | 4 |
On vérifie que les variables numériques sont numériques :
df.dtypes
Libellé object Produit object Prix int64 Quantite int64 dtype: object
On peut décider de conserver les guillements en spécifiant le paramètre quoting :
df2 = pandas.read_csv("exemple_fichier.txt", encoding="utf8" ,quoting=3)
df2
"Libellé" | "Produit" | "Prix" | "Quantite" | |
---|---|---|---|---|
0 | "L123" | "meuble" | "1000" | "1" |
1 | "L321" | "portable" | "500" | "2" |
2 | "L333" | "lampe" | "100" | "4" |
df2.dtypes
"Libellé" object "Produit" object "Prix" object "Quantite" object dtype: object
Et si jamais les virgules sont des points-virgules, il faut préciser le paramètre sep :
texte = """
"Libellé";"Produit";"Prix";"Quantite"
"L123";"meuble";"1000";"1"
"L321";"portable";"500";"2"
"L333";"lampe";"100";"4"
"""
with open("exemple_fichier2.txt", "w", encoding="utf8") as f:
f.write(texte)
df3 = pandas.read_csv("exemple_fichier2.txt", encoding="utf8", sep=";")
df3
Libellé | Produit | Prix | Quantite | |
---|---|---|---|---|
0 | L123 | meuble | 1000 | 1 |
1 | L321 | portable | 500 | 2 |
2 | L333 | lampe | 100 | 4 |
Et si jamais le fichier initial est très grand... On veut simplement lire les premières lignes :
df4 = pandas.read_csv("exemple_fichier2.txt", encoding="utf8", sep=";", nrows=2)
df4
Libellé | Produit | Prix | Quantite | |
---|---|---|---|---|
0 | L123 | meuble | 1000 | 1 |
1 | L321 | portable | 500 | 2 |
Ou encore une lecture par morceau de 2 lignes :
reader = pandas.read_csv("exemple_fichier2.txt", encoding="utf8", sep=";", iterator=True, chunksize=2)
for i, extrait in enumerate(reader):
print("extrait",i)
print(extrait)
extrait 0 Libellé Produit Prix Quantite 0 L123 meuble 1000 1 1 L321 portable 500 2 extrait 1 Libellé Produit Prix Quantite 0 L333 lampe 100 4