One way to store data permanently is to store it in files.
Edit a file
To edit a file in python we use the function open
.
This function takes as a first parameter the path of the file (relative or absolute) and as a second parameter the type of opening
Relative path / absolute path
A relative path in computing is a path that takes into account the read location.
An absolute path is a full path that can be read regardless of the read location.
The open function
Here is the syntax to read a file
>>> file = open ( "data.txt" , "r" ) >>> print file < open file 'data.txt' , mode 'r' at 0x7ff6cf3fe4b0 >
The second parameter Note that is informed by r
this parameter indicates a file open in reading .
Types of opening
There are several opening modes:
r , for read opening (READ). w , for opening for writing (WRITE), each time the file is opened, the content of the file is overwritten. If the file does not exist python creates it. a , for opening in append mode at the end of the file (APPEND). If the file does not exist python creates it. b , for opening in binary mode. t , for opening in text mode. x , create a new file and open it for writing
Closing a file
Like any open element, it must be closed once the instructions have been completed. For that we use the method close()
.
>>> file . close ()
Read the contents of a file
To display the entire contents of a file, you can use the read
on-file-object method .
# coding: utf-8 file = open ( "data.txt" , "r" ) print file . read () file . close ()
Write to file
Here is the syntax for writing to a file:
file = open ( "data.txt" , "a" ) file . write ( "Hello world" ) file . close ()
Note that for the opening world a
, if you want to write on the line, you can use the line break \n
:
file = open ( "data.txt" , "a" ) file . write ( " \ n Hello world" ) file . close ()
The keyword with
There is another shorter syntax that allows you to overcome the problem of closing the file: the keyword with
.
Here is the syntax:
with open ( "data.txt" , "r" ) as file : print file . read ()
No comments:
Post a Comment