In [1]:
path = 'data/src/test.txt'
In [2]:
f = open(path)
In [3]:
print(type(f))
In [4]:
f.close()
In [5]:
with open(path) as f:
print(type(f))
In [6]:
# with open('data/src/test_error.txt') as f:
# print(type(f))
# FileNotFoundError: [Errno 2] No such file or directory: 'data/src/test_error.txt'
In [7]:
with open(path) as f:
s = f.read()
print(type(s))
print(s)
In [8]:
with open(path) as f:
s = f.read()
print(s)
In [9]:
with open(path) as f:
l = f.readlines()
print(type(l))
print(l)
In [10]:
with open(path) as f:
l_strip = [s.strip() for s in f.readlines()]
print(l_strip)
In [11]:
with open(path) as f:
l = f.readlines()
print(l[1])
In [12]:
with open(path) as f:
for s_line in f:
print(s_line)
In [13]:
with open(path) as f:
s_line = f.readline()
print(s_line)
In [14]:
with open(path) as f:
while True:
s_line = f.readline()
print(s_line)
if not s_line:
break
In [15]:
path_w = 'data/src/test_w.txt'
In [16]:
s = 'New file'
with open(path_w, mode='w') as f:
f.write(s)
with open(path_w) as f:
print(f.read())
In [17]:
# with open('data/src/new_dir/test_w.txt', mode='w') as f:
# f.write(s)
# FileNotFoundError: [Errno 2] No such file or directory: 'data/src/new_dir/test_w.txt'
In [18]:
s = 'New line 1\nNew line 2\nNew line 3'
with open(path_w, mode='w') as f:
f.write(s)
with open(path_w) as f:
print(f.read())
In [19]:
l = ['One', 'Two', 'Three']
with open(path_w, mode='w') as f:
f.writelines(l)
with open(path_w) as f:
print(f.read())
In [20]:
with open(path_w, mode='w') as f:
f.write('\n'.join(l))
with open(path_w) as f:
print(f.read())
In [21]:
# with open(path_w, mode='x') as f:
# f.write(s)
# FileExistsError: [Errno 17] File exists: 'data/src/test_w.txt'
In [22]:
try:
with open(path_w, mode='x') as f:
f.write(s)
except FileExistsError:
pass
In [23]:
import os
if not os.path.isfile(path_w):
with open(path_w, mode='w') as f:
f.write(s)
In [24]:
with open(path_w, mode='a') as f:
f.write('Four')
with open(path_w) as f:
print(f.read())
In [25]:
with open(path_w, mode='a') as f:
f.write('\nFour')
with open(path_w) as f:
print(f.read())
In [26]:
with open(path_w, mode='r+') as f:
f.write('123456')
with open(path_w) as f:
print(f.read())
In [27]:
with open(path_w, mode='r+') as f:
f.seek(3)
f.write('-')
with open(path_w) as f:
print(f.read())
In [28]:
with open(path_w) as f:
l = f.readlines()
l.insert(0, 'FIRST\n')
with open(path_w, mode='w') as f:
f.writelines(l)
with open(path_w) as f:
print(f.read())