file_name = 'data_file_pointer.txt'
def print_txt(file_name):
try:
with open(file_name) as f:
for line in f.readlines():
print(line)
except FileNotFoundError as nf:
print(nf)
def clear_txt(file_name):
try:
with open(file_name,'r+') as f:
f.truncate()
except FileNotFoundError as nf:
print(nf)
try:
with open(file_name) as f:
print('r mode')
except FileNotFoundError as nf:
print(nf)
print('w:')
for i in range(3):
with open(file_name, 'w') as f:
f.write(str(i))
print_txt(file_name)
clear_txt(file_name)
print('a:')
for i in range(3):
with open(file_name, 'a') as f:
f.write(str(i))
print_txt(file_name)
print('字符模式:')
try:
with open(file_name) as f:
for c in f.read():
print(c, end=' ')
except FileNotFoundError as nf:
print(nf)
print()
print('字节模式:')
try:
with open('data1.txt', 'rb') as f:
for b in f.read():
print(b, end=' ')
except FileNotFoundError as nf:
print(nf)
print()
print('file pointer:')
try:
with open(file_name, 'w+') as f:
f.writelines(['qqqqqqqqqqq'])
except FileNotFoundError as nf:
print(nf)
print('1:')
print_txt(file_name)
try:
with open(file_name, 'w+') as f:
f.writelines(['hello python'])
except FileNotFoundError as nf:
print(nf)
print('2:')
print_txt(file_name)
try:
with open(file_name, 'r+') as f:
f.writelines(['123'])
except FileNotFoundError as nf:
print(nf)
print('3:')
print_txt(file_name)
try:
with open(file_name, 'r+') as f:
f.seek(20)
f.writelines(['123'])
except FileNotFoundError as nf:
print(nf)
print('4:')
print_txt(file_name)
try:
with open(file_name, 'w+') as f:
f.seek(20)
f.writelines(['hello word'])
except FileNotFoundError as nf:
print(nf)
print('5:')
print_txt(file_name)
try:
with open(file_name, 'a+') as f:
f.seek(1)
f.writelines(['hello word'])
except FileNotFoundError as nf:
print(nf)
print('6:')
print_txt(file_name)