Python基础之文件操作

文件的三种打开方式

# 假设有一个 文件test, 存的是nick is handsome
## 只读
f = open('test', 'r', encoding = 'utf8')
print(f.read())

## 用这个方式循环文件
for i in f:
	print(i)
f.close() #记得关闭文件

## 读二进制
f = open('test', 'rb')
data = f.read()
print(data)
print(f"type(data): {type(data)}")
f.close()

## 只写
f = open('test', 'w', encoding='utf8')
lt = ['sdkjle', 'sidkldfjfid']
res = ''.join(lt)
f.write(res) ##会在test中显示拼接好的字符串 #清空后再写
f.close()

##追加值(不会等到清空)
f = open('test', 'a', encoding='utf8')
f.write('
nick handsome') #会在下一行加入此值
f.close()

##只读

nick is handsome

##循环文件

nick is handsome

##读二进制

b'sdkjle sidkldfjfid nick handsome' type(data): <class 'bytes'>

只写

sdkjle sidkldfjfid

追加值

sdkjle sidkldfjfidnick

handsome

with管理文件操作上下文

## 赋值给f,f.read()
with open('test', 'rt', encoding='utf8') as f:
	print(f.read())
	
## 多个文件一次性打开
with open('test', 'rt') as fr,
		open('tst', 'wt') as fw:
	fw.write(fr.read())

##用f打印test

``sdkjle sidkldfjfid`

nick handsome

##test文件中的内容写入tst中

sdkjle sidkldfjfid

nick handsome

原文地址:https://www.cnblogs.com/michealjy/p/11316230.html