python 文件操作之open,read,write

1、open

#open(filepath , 'mode')

file = open(‘D:\test\test.txt’,‘w’)   #存在问题见FAQ1

一般常用模式:r(只读)、w(只写)、a(追加)、b(二进制)

组合:r+(读写)、w+(读写)  #存在问题见FQA2

2、读文件(r): read()         readline()           readlines()

file = open('D/test/test.txt','r')   #只读模式打开file

all_txt = file.read()  #读全部

one_line_txt = file.readline()   #读一行

all_line_txt = file.readlines()  #读所有行

 

3、读固定字节文件

file = open('D/test/test.txt','b')   #只读模式打开file

200_byte = file.read(200)

 

4、写文件(w)

file = open('D/test/test.txt','w')   #只写模式打开file

 input= file.write('11111')

list = ['1111','22222','33333']

input_lines = file.writelines(list)  #写入的参数放入一个列表中,写多行

 

https://docs.python.org/2.7/tutorial/inputoutput.html#methods-of-file-objects

FQA1:报错

 

无效的模式或者文件

 

关于python绝对路径的书写方式

 

  • 改为file = open(r‘D:\test\test.txt’,‘w’) 
  • 改为file = open('D:/test/test.txt’,‘w')  表示绝对路径是使用正斜杠

 

FAQ2:

读写模式在windows 下,同时调用会出现乱码。尽量分开使用

https://segmentfault.com/q/1010000000397712

 

转载于:https://www.cnblogs.com/wang0331/p/7083090.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值