python中的writelines函数_python writelines()函数

在博客(Python本地数据获取   网址:http://blog..net/sxingming/article/details/51333663)中,我们详细介绍了python中文件读写的各种方法。

本文通过例子具体示例一下writelines( )函数的使用,所用的例子是向文件"C:\Users\Administrator\Desktop\test.txt"中写入数据。

1》writelines()函数最常用的方式如下:

>>> f=open(r"C:\Users\Administrator\Desktop\test.txt",'w')

>>> f.writelines(['love\n','python\n','love python\n']) #向文件中写入3行数据

>>> f.close()

运行结果如下:

63cc3f4c97252384c0f57739361c6ebf.png

2》若列表中字符串的末尾没有换行符,则相当于写入了一行数据,如下:

>>> f=open(r"C:\Users\Administrator\Desktop\test.txt",'w')

>>> f.writelines(['love','python','love python'])

>>> f.close()

运行结果如下:

5a3366c3447aafdf3f86eb5f2e3b37fe.png

3》writelines()函数的参数也可以是一个字符串,用法跟write()函数类似。

>>> f=open(r"C:\Users\Administrator\Desktop\test.txt",'w')

>>> f.writelines('love\npython\nlove python\n')

>>> f.close()

运行结果如下:

a3ac4a39bb61cb52f445bad25d2fa0b3.png

>>> f=open(r"C:\Users\Administrator\Desktop\test.txt",'w')

>>> f.writelines('lovepythonlove python')

>>> f.close()

运行结果如下:

9a1a4397ce7c2dcc68b513dfcea9884a.png

(完)


版权声明:本文为weixin_39858275原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。