Python基础——文件操作

写文件

writefile

%%writefile ./data/testFile.txt
hello python
jin tian tian qi bu cuo

   

open覆盖

txt=open('./data/testFile.txt','w')#w会覆盖原内容
txt.write('jin tian tian qi bu cuo\n')
txt.write('hello python\n')
txt.close()

   

open追加

txt=open('./data/testFile.txt','a')#a会追加
txt.write('123\n')
txt.write('456\n')
txt.close()

   

写入异常

txt=open('./data/testFile.txt','w')
try:
    for i in range(100):
        10/(i-50)
        txt.write(str(i)+'\n')
except Exception:
    print("error:",i)
finally:
    txt.close()

   

   

读文件

   

读取所有内容

txt=open('./data/testFile.txt')
txt_read=txt.read()
print(txt_read)

   

按行读取

txt=open('./data/testFile.txt')
lines=txt.readlines()
print(lines)
print(type(lines))
for line in lines:
    print('cur_line:',line)

   

open读取

txt=open('./data/testFile.txt','w')#w会覆盖原内容
for i in range(5):
    txt.write(str(i)+'\n')
txt.close()

txt1=open('./data/testFile.txt','r')#r是读取
print(txt1.read())
txt1.close()

   

关闭文件

   

使用open打开后,一定要记得使用close关闭。

写入时打开,如果不关闭,则内容无法写入,内容是在关闭时写入文件的。

txt.close()

   

打开后自动关闭

with open('./data/testFile.txt','w') as f:
    try:
        for i in range(100):
            10/(i-50)
            f.write(str(i)+'\n')
    except Exception:
        print("error:",i)

转载于:https://www.cnblogs.com/gloria-zhang/p/10607263.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值