📚 The CoCalc Library - books, templates and other resources
License: OTHER
Kernel: Python 2
This notebook was prepared by Donne Martin. Source and license info is on GitHub.
Files
Read a File
Write a File
Read and Write UTF-8
Read a File
Open a file in read-only mode.<br> Iterate over the file lines. rstrip removes the EOL markers.<br>
In [1]:
Out[1]:
class TypeUtil:
@classmethod
def is_iterable(cls, obj):
"""Determines if obj is iterable.
Useful when writing functions that can accept multiple types of
input (list, tuple, ndarray, iterator). Pairs well with
convert_to_list.
"""
try:
iter(obj)
return True
except TypeError:
return False
@classmethod
def convert_to_list(cls, obj):
"""Converts obj to a list if it is not a list and it is iterable,
else returns the original obj.
"""
if not isinstance(obj, list) and cls.is_iterable(obj):
obj = list(obj)
return obj
Write to a file
Create a new file overwriting any previous file with the same name, write text, then close the file:
In [2]:
Read and Write UTF-8
In [3]: