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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Django模板变量如何传递给外部js调用的方法小结

前言 因为工作的需要,最近一直在思考如何更好的组织Django中的静态资源,比如JS、CSS一类,如何结合前端构建工具写出更好的代码以及结构呢?下面这篇文章就给大家详细介绍了实现的方法,...

python3中获取文件当前绝对路径的两种方法

方法1: import sys print(sys.argv) 得到文件当前绝对路径字符串的一个列表 ['D:/pycharm/PracticeProject/ClientSe...

Python基于百度云文字识别API

本文实例为大家分享了Python实现最简单的文字识别的具体代码,供大家参考,具体内容如下 Python版本:3.6.5 百度云提供的文字识别技术,准确率还是非常高的,而且每天还有5w次免...

python实现dict版图遍历示例

复制代码 代码如下:#_*_coding:utf_8_import sysimport os class Graph():    def __init__(...

python enumerate函数的使用方法总结

enumerate函数用于遍历序列中的元素以及它们的下标。 enumerate函数说明: enumerate()是python的内置函数 enumerate在字典上是枚举、列举的意思...