In [1]:
import pathlib
import os

In [2]:
os.makedirs('temp', exist_ok=True)

In [3]:
p_empty = pathlib.Path('temp/empty_file.txt')

In [4]:
print(p_empty)


temp/empty_file.txt

In [5]:
print(type(p_empty))


<class 'pathlib.PosixPath'>

In [6]:
print(p_empty.exists())


False

In [7]:
p_empty.touch()

In [8]:
print(p_empty.exists())


True

In [9]:
p_empty.touch()

In [10]:
# p_empty.touch(exist_ok=False)
# FileExistsError: [Errno 17] File exists: 'temp/empty_file.txt'

In [11]:
# pathlib.Path('temp/new_dir/empty_file.txt').touch()
# FileNotFoundError: [Errno 2] No such file or directory: 'temp/new_dir/empty_file.txt'

In [12]:
p_empty_new = pathlib.Path('temp/new_dir/empty_file.txt')
p_empty_new.parent.mkdir(parents=True, exist_ok=True)
p_empty_new.touch()

In [13]:
pathlib.Path('temp/empty_file2.txt').touch()

In [14]:
p_new = pathlib.Path('temp/new_file.txt')

In [15]:
print(p_new.exists())


False

In [16]:
with p_new.open(mode='w') as f:
    f.write('line 1\nline 2\nline 3')

In [17]:
with p_new.open() as f:
    print(f.read())


line 1
line 2
line 3

In [18]:
s = p_new.read_text()

In [19]:
print(s)


line 1
line 2
line 3

In [20]:
print(type(s))


<class 'str'>

In [21]:
i = p_new.write_text('new text')

In [22]:
print(i)


8

In [23]:
print(p_new.read_text())


new text

In [24]:
p_new2 = pathlib.Path('temp/new_file2.txt')

In [25]:
print(p_new2.exists())


False

In [26]:
# print(p_new2.read_text())
# FileNotFoundError: [Errno 2] No such file or directory: 'temp/new_file2.txt'

In [27]:
print(p_new2.write_text('new text2'))


9

In [28]:
print(p_new2.read_text())


new text2

In [29]:
# print(pathlib.Path('temp/new_dir2/new_file.txt').write_text('new_text'))
# FileNotFoundError: [Errno 2] No such file or directory: 'temp/new_dir2/new_file.txt'

In [30]:
p_text_new = pathlib.Path('temp/new_dir2/new_file.txt')
p_text_new.parent.mkdir(parents=True, exist_ok=True)
print(p_text_new.write_text('new_text'))


8

In [31]:
print(p_text_new.read_text())


new_text

In [32]:
print(pathlib.Path('temp/new_file3.txt').write_text('new_text3'))


9

In [33]:
print(pathlib.Path('temp/new_file3.txt').read_text())


new_text3

In [34]:
p_empty = pathlib.Path('temp/empty_file.txt')

In [35]:
print(p_empty.exists())


True

In [36]:
p_empty.unlink()

In [37]:
print(p_empty.exists())


False

In [38]:
# p_empty.unlink()
# FileNotFoundError: [Errno 2] No such file or directory: 'temp/empty_file.txt'

In [39]:
p_dir = pathlib.Path('temp/')

In [40]:
# p_dir.unlink()
# PermissionError: [Errno 1] Operation not permitted: 'temp'

In [41]:
for p in p_dir.iterdir():
    if p.is_file():
        p.unlink()

In [42]:
[p.unlink() for p in p_dir.iterdir() if p.is_file()]


Out[42]:
[]

In [43]:
import shutil

shutil.rmtree('temp')