示例代码
f =
open(
'1abv.txt',
'w')
list1 = [
'1',
'2',
'3']
f.writelines(list1)
f.
close()
f =
open(
'1abv.txt',
'w')
list1 = [
1,
2,
3]
f.writelines(list1)
f.
close()
3、正确示例,字符列表一行行写
f =
open(
'1abv.txt',
'w')
list1 = [
1,
2,
3]
for i
in list1:
f.
write(i)
f.
close()
解释
—–python写文件,首先是先创建file对象,然后调用file对象的写单行函数write(),以及写多行函数writelines(),值得注意的是,无论是单行写还是多行写,python重要的是只支持字符或者是字符串的写, 如上面第二个例子,如果列表是整形的,那么就会报下面这个错误,还有就是python写文件后,一定要close(),不然的话,文件是不会创建的。
Traceback (most recent call
last):
File
"<input>",
line 4,
in <module>
TypeError: expected
a string or other
character buffer object
总结
——-每天进步一点点,自己也是在用python的过程中把自己遇到的问题,写出来,给大家分享。