python学习Day13-文件操作

文件基本操作

%%writefile tang.txt
hello python
java
tian qi hen hao
Writing tang.txt

打开文件(open)

# ./是当前文件夹
txt = open('./tang.txt')
print(txt)
<_io.TextIOWrapper name='./tang.txt' mode='r' encoding='cp936'>

读取文件(read)

txt_read = txt.read()
print(txt_read)
hello python
java
tian qi hen hao

读取文件并放入列表中(readlines)每一行一个元素

lines = txt.readlines()
print(type(lines))
print(lines)
<class 'list'>
['hello python\n', 'java\n', 'tian qi hen hao\n']
for line in lines:
    print('xur_line:',line)
xur_line: hello python

xur_line: java

xur_line: tian qi hen hao

关闭文件(close)

txt.close()

写文件('w’覆盖,‘a’追加)

txt = open('tang_write2.txt','w')
txt.write('hello java\n')
txt.write('python\n')
txt.write('tian qi hen hao')
15
txt.close()
txt = open('tang_write.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
hello java
python
tian qi hen hao
txt = open('tang_write.txt','w')
txt.write('123\n')
txt.write('456\n')
txt.write('789')
txt.close()
txt = open('tang_write.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
123
456
789
txt = open('tang_write.txt','a')
txt.write('hello java\n')
txt.write('python\n')
txt.write('tian qi hen hao')
txt.close()
txt = open('tang_write.txt')
txt_read = txt.read()
print(txt_read)
txt.close()
123
456
789hello java
python
tian qi hen hao

写文件必须关闭文件

txt = open('tang_write.txt','w')
for i in range(100):
    txt.write(str(i)+'\n')
txt2 = open('tang_write.txt','r')
print(txt2.read())
txt = open('tang_write.txt','w')
for i in range(5):
    txt.write(str(i)+'\n')
txt.close()
txt2 = open('tang_write.txt','r')
print(txt2.read())
0
1
2
3
4

注意:执行完写操作后,如果不关闭,是没有写进文件里面的

异常处理,及时保护文件

txt = open('tang_write.txt','w')
try:
    for i in range(10):
        10/(i-5)
        txt.write(str(i)+'\n')
except Exception:
    print('error:',i)
finally:
    txt.close()
error: 5
txt = open('tang_write.txt','r')
txt_read = txt.read()
print(txt_read)
txt.close()
0
1
2
3
4

执行完自动关闭(with…as…)

with open('tang_write.txt','w') as f:
    f.write('tian qi henhao')
with open('tang_write.txt','r') as f:
    print(f.read())
tian qi henhao

未完待续

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值