python中的write()和open()

filename = ‘pragramming.txt’

with open(filename,‘w’) as fileobject: #使用‘w’来提醒python用写入的方式打开
fileobject.write(‘I love your name!’
‘\nI love your cloth!’
‘\nI love your shoes!’
‘\nI love your hair!’)

with open(filename,‘a’) as fileobject: #使用‘a’来提醒python用附加模式的方式打开
fileobject.write(’\nI an superman.’)

代码中的filename如果没有这个文件,python会自己新建一个。

json文件的写入和读取:

import json

filename = ‘number.json’
def write_json():
numbers = [1,2,3,4,5,6,7,8,9,10]
with open(filename,‘w’) as fp:
json.dump(numbers,fp)#写入json文件
write_json()

def read_json():
with open(filename) as pf:
numbers = json.load(pf)#读取json文件
print(numbers)
read_json()

训练:

import json
def remember_me():
active = True
while active:
for i in range(5):
if i < 4:
username = input(‘Please enter your name:’)
filename = ‘name.json’
with open(filename,‘w’) as fp:#以w的方式打开写入时会覆盖原有记录,而以a打开不会
json.dump(username,fp)
print('Hello! '+username.title())
else:
active = False
remember_me()

open函数的一些注意点
open(file[, mode[, buffering[, encoding[, errors[, newline]]]]])
(1)file文件路径及名称,需要加引号如”/Users/macxunlei/Desktop/a.txt”
(2)mode文件打开模式,r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用、
(3)buffering的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;
(4)encoding表示的是返回的数据采用何种编码方式进行解码,一般采用’utf-8’或者’gbk’;读文件相当于解码过程,这个解码过程的默认编码(encoding为空)为系统决定的,若是windows默认为gbk,若是linux、max默认utf-8,只有这个默认编码和文件存储时编码一致才不会出现乱码。
(5)errors的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序
(6)newline可以取的值有None, \n, \r, ”, ‘\r\n’,用于区分换行符,但是这个参数只对文本模式有效;

下面就mode中的r,r+,w,w+,a,a+作一下区分:

python中的write()和open()