Python---file

import locale
import io
import gzip
import sys
class RedirectStdoutTo:
	def __init__(self, out_new):
		self.out_new = out_new

	def __enter__(self):
		self.out_old=sys.stdout
		sys.stdout=self.out_new
	
	def __exit__(self,*args):
		sys.stdout=self.out_old

'''
if one class has __enter__and __exit__, then it is context mamanger
'''

def open1(path):
	file1=open(path, encoding='utf-8')
	print(file1.read())
	print(file1.name)
	print(file1.mode)
	print(file1.encoding)
	print(file1.read())
	print(file1.tell())
	print(file1.seek(0))
	print(file1.read(1))
	print(file1.tell())
	print(file1.read())
	file1.close()
	print(file1.closed)

def open2(path):
	print('===============open2=================')
	with open(path, encoding='utf-8') as file2:
		print(file2.read())

def open3(path):
	print('==============open3======================')
	linenm=0;
	with open(path, encoding='utf-8') as file3:
		for line1 in file3:
			linenm+=1
			print('{:>4}{}'.format(linenm, line1.rstrip()))
	
def open4(path):
	print('==============open4============================')
	with open(path, mode='a', encoding='utf-8') as file4:
		'''attention, w means rewrite, r means append'''
		file4.write('add new line\n')

def open5(path):
	print('==============open5=================================')
	with open(path, mode='rb') as file5:
		'''no need pass encoding, because we're passing b--byte,binary'''
		print(file5.read(100))

def open6():
	print('=============open6=========================================')
	string1='I want to make this string as file'
	file6=io.StringIO(string1)
	print(file6.tell())
	print(file6.read())

def open7(path):
	print('===============open7=======================================')
	with gzip.open(path, mode='ab') as file7:
		file7.write('I add new line in gz file\n'.encode('utf-8'))

def open8(path):
	print('=============open8====================================')
	with open(path, mode = 'a', encoding ='utf-8') as file8, RedirectStdoutTo(file8):
		print('haha, my print is appended into files, not in console\n')
	
	with open(path, mode = 'a', encoding ='utf-8') as file8:
		with RedirectStdoutTo(file8):
			print('haha, my print is appended into file again\n')
'''
with can be without "as"
open is an context manager, because open() api return stream, 
it is context manager implemented __enter__,__exit__
RedirectStdoutTo is also context manager
'''


def getdefault():
	print(locale.getpreferredencoding())

if __name__ == '__main__':
	getdefault()
	open1('file_util_m.txt')
	open2('file_util_m.txt')
	open3('file_util_m.txt')
	open4('file_util_m.txt')
	open5('metro.jpg')
	open6()
	open7('file.gz')
	open8('file_util_m.txt')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值