Python used to read and write a file open function, the open function of the first parameter is the file name, the second parameter is optional, there are four common modes:
(. 1) R & lt
opens a file to read the data, which is the default mode ;
(2) W
opens a file for writing the data, if the data file already, it will clear the first data;
(. 3) a
opens a file and add data to the end of the file;
(. 4) X
to open a new file to write the data, if the file already exists failed;
2 to 4 kinds of mode if the first argument specifies the file does not exist, it will create an empty file.
Examples:
1, write files
= Open Todos ( ' named text.txt in ' , ' A ' ) # to "append mode" File Open Print ( ' ABC ' , File = Todos) # is written into a file stream Todos Print ( ' 123 ' , File = Todos) todos.close () # close the file stream
Python for experienced open file operation process, shut down the process.
With statements by simplifying the code that can automatically call close at the end of the code group
with open('text.txt', 'a') as todos: print('abc', file = todos) print('123', file = todos)
2, read the file
= Open rows ( ' named text.txt in ' ) # the second parameter is optional, is not written to read the default mode for Row in rows: print (Row, End = '' ) # replace the default print spaces newline rows.close ()
Simplify the code with the with statement
with open('text.txt') as rows: for row in rows: print(row, end='')