初识Python之将数据写入文件 您所在的位置:网站首页 python往文件里写数据 初识Python之将数据写入文件

初识Python之将数据写入文件

#初识Python之将数据写入文件| 来源: 网络整理| 查看: 265

自己弄了一个python学习群,感兴趣的可以加在这里插入图片描述

上一篇介绍了从文件中读取数据,这一篇我们来说说如何把数据写入到文件中

存数据的最简单的方式之一是将其写入到文件中

上一篇我们用到的函数是read(),那么这一篇我们用到的函数叫做write()

回顾: with open('E:\\pythonLearn\\12194548.txt') as file_object: contents = file_object.read() print(contents) 或者 file_object = open('12194548.txt') contents = file_object.read() print(contents)

建议采用第一种,原因在上一篇已经介绍过了,不在赘述

将单行数据写入到空白文本中 with open('12194548.txt', 'w') as file_object: file_object.write('hello world')

问题:上面的路径叫什么路径?

在这个示例中,调用open()时提供了两个实参。

第一个实参也是要打开的文件的名称

第二个实参(‘w’)告诉Python,我们要以什么模式打开这个文件

有以下几种打开模式:

读取模式(‘r’)写入模式(‘w’)附加模式(‘a’)读取和写入模式(‘r+’)

在上一篇读取文件中的数据中我们并没有写入第二个参数,但是我们还是可以读取出来数据,Python也没有报错。这是因为Python是默认以只读模式来打开文件

当然了我们在写入的时候可能会遇到要写如的文件不存在,在read()中,python会直接抛出异常,而在写入中函数open()将自动创建它

注意:以写入(‘w’)模式打开文件时千万要小心,因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件

将多行数据写入到空白文本中

如果你对读取数据那一片还有印象的话,你应该会记得,每一行后面都会有一个换行符

回顾 with open('12194548.txt') as file_object: contents = file_object.readlines() print(contents)

输出:

['aaa\n', '\n', ' bbb']

但是这里不一样了,函数write()不会在你写入的文本末尾添加换行符

所以

with open('12194548.txt', 'w') as file_object: file_object.write('hello world') file_object.write('hello world1') file_object.write('hello world2')

运行之后并不是你期望的

hello world hello world1 hello world2

而是

hello worldhello world1hello world2

所以我们需要手动添加换行符

with open('12194548.txt', 'w') as file_object: file_object.write('hello world\n') file_object.write('hello world1\n') file_object.write('hello world2\n') 附加数据到文件 上面说了w会直接清空文件,这对于我们来说是很不合理的,很多时候我们只需要在原数据后面附加,Python给我们提供了 a 模式 with open('12194548.txt', 'a') as file_object: file_object.write('hello world\n') file_object.write('hello world1\n') file_object.write('hello world2\n')

文件中结果:

hello world hello world1 hello world2 hello world hello world1 hello world2 勤动手

记录每一位访问者:

name = input("来者何人:") with open('12194548.txt', 'a') as file_object: file_object.write(name + '\n')

记录每一位访问者,并对他们进行问候

name = input("请输入姓名:") welcome = '欢迎欢迎,热烈欢迎' with open('12194548.txt', 'a') as file_object: file_object.write(name + '到了\n') file_object.write('列队欢迎\n') file_object.write(welcome + '\n') file_object.write('=========等待下一位来访者==========\n')

copy 文件

with open('12194548.txt') as file_object: with open('12194548copy.txt', 'w') as write_file_object: for line in file_object: write_file_object.write(line)

很简单的完成了文件的复制,你想存储到不同的路径可以在写文件中路径更改

关注公众号:Python互助小组 一起学习,共同进步 里面有不定期的赠书活动哦 公众号:Python互助小组 或者搜索python_group



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有