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)
In [5]:
print(type(p_empty))
In [6]:
print(p_empty.exists())
In [7]:
p_empty.touch()
In [8]:
print(p_empty.exists())
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())
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())
In [18]:
s = p_new.read_text()
In [19]:
print(s)
In [20]:
print(type(s))
In [21]:
i = p_new.write_text('new text')
In [22]:
print(i)
In [23]:
print(p_new.read_text())
In [24]:
p_new2 = pathlib.Path('temp/new_file2.txt')
In [25]:
print(p_new2.exists())
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'))
In [28]:
print(p_new2.read_text())
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'))
In [31]:
print(p_text_new.read_text())
In [32]:
print(pathlib.Path('temp/new_file3.txt').write_text('new_text3'))
In [33]:
print(pathlib.Path('temp/new_file3.txt').read_text())
In [34]:
p_empty = pathlib.Path('temp/empty_file.txt')
In [35]:
print(p_empty.exists())
In [36]:
p_empty.unlink()
In [37]:
print(p_empty.exists())
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')