Sous python pour créer un fichier il suffit d'utiliser la commande suivante:
>>> f = open('MonFichier.txt','w')
Attention: si le fichier existe déjà il va écraser celui-ci. Il est donc conseillé de verifier au préalable si le fichier existe déjà dans votre répertoire courant. Pour cela vous pouvez procéder comme suit:
>>> import os.path>>> os.path.isfile('test.txt')False>>> os.path.isfile('MonFichier.txt')True>>> if not os.path.isfile('myfile.txt'):... f = open('MonFichier.txt','w')... do something... f.close()
Pour ensuite écrire dans le fichier il y a la fonction f.write(), exemple
>>> f = open('MonFichier.txt','w')>>> f.write('hello')>>> f.close()
Attention vous ne pouvez écrire dans le fichier que des strings. Si vous voulez écrire un nombre dans le fichier il faut d'abord convertir celui-ci en string comme dans cet exemple"
>>> f.write(str(123))
Vous pouvez écrire plusieurs fois dans le fichier:
>>> f = open('MonFichier.txt','w')>>> f.write('hello')>>> f.write(str(123))>>> f.write('how are you ?')>>> f.close()
Si vous voulez aller à la ligne il faut utiliser la balise \n:
>>> f = open('MonFichier.txt','w')>>> f.write('hello \n')>>> f.write(str(123) + '\n')>>> f.write('how are you ? \n')>>> f.close()
Note: Pour écrire des données il est préférable de passer par numpy voir: numpy.savetxt.
Recherches associées
| Liens | Site |
|---|---|
| Input and Output | python doc |
| Correct way to write line to file in Python | stackoverflow |
| Check if a file exists using Python? | stackoverflow |
| Write file with specific permissions in Python | stackoverflow |
| numpy.savetxt | numpy doc |
