Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated best practices method using pathlib #140

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion docs/maintainability/not_using_with_to_open_files.rst
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,33 @@ The modified code below is the safest way to open a file. The ``file`` class has
content = f.read()
# Python still executes f.close() even though an exception occurs
1 / 0
Pathlib makes the simple cases simpler
...........................
The pathlib module makes several complex cases somewhat simpler, but it also makes some of the simple cases even simpler. We could open the file, read its contents and close the file using a with block. As shown above, but there is another way to do that using pathlib:

.. code:: python

from pathlib import Path
p = Path('file.txt')
p.read_text()

Using the above code we can not add mode(default is read mode), to do so there is another way mentioned below:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

typo mode(default is missing a space

The modes could be

- rt : read text
- wr : write text
- at : append text


.. code:: python

path = Path('file.txt')
with open(path, mode='at') as f:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

with path.open("at") as f:

f.write('# config goes here')


References
----------

`effbot - Understanding Python's with statement <http://effbot.org/zone/python-with-statement.htm>`_