
上QQ阅读APP看书,第一时间看更新
4.2.3 写入数据
往一个文件中写入一个字符串可以用write()方法,写入一个字符串列表或元组可以用writelines()方法,用writeable()方法可以检查文件对象是否可以写入。
1.用write()方法写数据
文件对象的write()方法逐行向文件中写入一个字符串数据,格式为write(text),其中text是字符串。write()方法不会在被写入的字符串后面加换行符“\n”,需要手动在每个字符串后加入“\n”。
下面的程序先用自定义函数readData()从student.txt文件中读取学号、姓名和各科成绩,返回二维数据列表;然后用student类创建实例对象,赋予对象数据,把对象放到一个字典中,在字典中计算总分和平均分;最后按照学生顺序,把实例中的数据写到文件中。输入和输出的文件内容如图4-2所示。

图4-2 输入和输出文件内容


Python默认的文件编码是“GBK”,即unicode形式,要想转成其他编码格式,如“UTF-8”或“UTF-16”,可以用字符串的encode()方法进行转换,例如下面的程序。

2.用writelines()方法写数据
writelines()方法可以把一个字符串列表或元组输出到文件中,其格式为writelines (lines)。writelines()方法不会自动在每个字符串列表的末尾加“\n”,例如下面的代码。
