Opening the file in writing mode

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jan 15 06:33:06 EST 2015


Abdul Abdul wrote:

> Hello,
> 
> In the Python documentation, when opening the file in write mode, it
> mentions the following:
> 
> *writing (truncating the file if it already exists)*
> What is meant by "truncating" here? Is it simply overwriting the file
> already existing?

Not quite. It means that if the file already has content, the content is
erased immediately you open it, not just as you write over the top.

Consider this demo:


fname = 'test'  # caution, this file will be overridden
for mode in ('w', 'r+w'):
    # first write a file with known content
    with open(fname, 'w') as f:
        f.write("hello world\n")
    # confirm the file contains what we expect
    with open(fname, 'r') as f:
        assert f.read() == "hello world\n"
    # now test the mode
    with open(fname, mode) as f:
        f.write("xxxx")
    with open(fname, 'r') as f:
        print (mode, f.read())


The output of running this code will be:

('w', xxxx'')
('r+w', 'xxxxo world\n')



-- 
Steven




More information about the Python-list mailing list