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字符串与url编码的转换实例

主要应用的场景 爬虫生成带搜索词语的网址 1.字符串转为url编码 import urllib poet_name = "李白" url_code_name = urllib.quo...

Python 进程之间共享数据(全局变量)的方法

进程之间共享数据(数值型): import multiprocessing def func(num): num.value=10.78 #子进程改变数值的值,主进程跟着改变...

Matplotlib scatter绘制散点图的方法实现

Matplotlib scatter绘制散点图的方法实现

前言 考虑到很多同学可能还没有安装matplotlib包,这里给大家提供我常用的安装方法。首先Win键 + R,输入命令cmd打开命令行工具,再次在命令行工具中输入pip install...

Pytorch中的variable, tensor与numpy相互转化的方法

Pytorch中的variable, tensor与numpy相互转化的方法

在使用pytorch作为深度学习的框架时,经常会遇到变量variable、张量tensor与矩阵numpy的类型的相互转化的问题,本章结合这实际图像对此转化方法进行实现。 1.加载需要用...

python实现字符串连接的三种方法及其效率、适用场景详解

python字符串连接的方法,一般有以下三种: 方法1:直接通过加号(+)操作符连接 website = 'python' + 'tab' + '.com' 方法2:join方法...