Python3写入文件常用方法实例分析

yipeiwu_com5年前Python基础

本文实例讲述了Python3写入文件常用方法。分享给大家供大家参考。具体如下:

''''' 
Created on Dec 18, 2012 
写入文件 
@author: liury_lab 
''' 
# 最简单的方法
all_the_text = 'hello python'
open('d:/text.txt', 'w').write(all_the_text)
all_the_data = b'abcd1234'
open('d:/data.txt', 'wb').write(all_the_data)
# 更好的办法
file_object = open('d:/text.txt', 'w') 
file_object.write(all_the_text)
file_object.close()
# 分段写入
list_of_text_strings = ['hello', 'python', 'hello', 'world']
file_object = open('d:/text.txt', 'w')
for string in list_of_text_strings:
  file_object.writelines(string)
list_of_text_strings = ['hello', 'python', 'hello', 'world']
file_object = open('d:/text.txt', 'w')
file_object.writelines(list_of_text_strings)

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python编写简单的HTML页面合并脚本

最近写一个BootStrap页面...因为功能需要所以决定一个页面解决所有问题,然后用jQuery来动态显示功能....然而这样做的话页面会相当庞大,一堆隐藏模态窗口和功能div都堆在一...

pytorch实现用CNN和LSTM对文本进行分类方式

model.py: #!/usr/bin/python # -*- coding: utf-8 -*- import torch from torch import nn imp...

Flask-WTF表单的使用方法

flask_wtf是flask框架的表单验证模块,可以很方便生成表单,也可以当做json数据交互的验证工具,支持热插拔。 安装 pip install Flask-WTF Fla...

Python实现搜索算法的实例代码

将数据存储在不同的数据结构中时,搜索是非常基本的必需条件。最简单的方法是遍历数据结构中的每个元素,并将其与您正在搜索的值进行匹配。这就是所谓的线性搜索。它效率低下,很少使用,但为它创建一...

Django csrf 两种方法设置form的实例

第一种方法,在视图函数上边添加一条语句 @csrf_exempt 例子: @csrf_exempt def login(request): return render_to_...