首页 > 编程语言 > 详细

python 文件操作之open,read,write

时间:2017-06-27 07:59:03      阅读:268      评论:0      收藏:0      [点我收藏+]

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

 

python 文件操作之open,read,write

原文:http://www.cnblogs.com/wang0331/p/7083090.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!