Reading and Writing Files
open() returns a file object, and is most commonly used with two arguments: open(filename, mode).
>>>
f=
open
('workfile'
,'w'
)
- mode ‘r‘ when the file will only be read.
- mode ‘w‘ for only writing (an existing file with the same name will be erased).
- mode ‘a‘ opens the file for appending, any data written to the file is automatically added to the end.
- mode ‘r+‘ opens the file for both reading and writing.
Read content file: the default when reading is to convert platform-specific line endings (\n on Unix, \r\n on Windows) to just \n
>>>
with
open
('workfile'
)as
f:>>>
read_data=
f.read
()
Write text into a file
>>>
f=
open
('workfile'
,'r+'
)>>>
f.write
('This is a test\n'
)