python文件的读写

‘’’
python文件读取:
文件读写基本步骤:1.open:打开一个文件对象;2.read:读取整个文件;3.close:文件使用完毕后必须关闭,因为
文件对象会占用操作系统资源,操作系统同一时间能打开的文件数量也是有限的
with open:文件读写时有可能产生异常,一旦出现异常,后面的close()方法就不会调用
逐行读取:readline();readlines()
python文件写入:
已写入模式打开文件 with open(file,‘w’) as file_object:
写入多行
已追加的方式写入文件 with open(file,‘a’) as file_object:
‘’’

#open
file_object=open(r’C:\Users\Administrator\Desktop\123.txt’)
#read
contents=file_object.read()
print(contents)
#close
file_object.close()

#with open
with open(r’C:\Users\Administrator\Desktop\123.txt’) as file_object:
contents=file_object.read()
print(contents)

#readline
file=r’C:\Users\Administrator\Desktop\123.txt’
with open(file) as file_object:
contents=file_object.readline()
print(contents)

#readline
file=r’C:\Users\Administrator\Desktop\123.txt’
with open(file) as file_object:
contents=file_object.readlines()
print(contents)
#strip,去除字符串两端的空格及换行
print(contents[0].strip())
#使用for循环
L=[]
for i in contents:
L.append(i.strip())
print(L)

#写入文件
file=r’C:\Users\Administrator\Desktop\123.txt’
with open(file,‘w’) as file_object:
file_object.write(“I Love Python”)

#写入多行
file=r’C:\Users\Administrator\Desktop\123.txt’
with open(file,‘w’) as file_object:
file_object.write(“I love china\n”)
file_object.write(“I love Python”)

#以追加的方式写入文件
file=r’C:\Users\Administrator\Desktop\123.txt’
with open(file,‘a’) as file_object:
file_object.write(“I love china\n”)
file_object.write(“I love Python”)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值