python基础(5)-文件操作
文件(file)操作
创建文件

verse.txt:
床前明月光 疑是地上霜
open(path(文件路径),mode(模式:r/r+[读],w/w+[写],a/a+[追加])):返回文件句柄(对象)
verse_file = open('verse.txt','r',encoding="utf-8")
r/r+[读],w/w+[写],a/a+[追加]的区别
| mode | 可做操作 | 若文件不存在 | 是否覆盖 |
| r | 只读 | 报错 | - |
| r+ | 读写 | 报错 | 是 |
| w | 只写 | 创建 | 是 |
| w+ | 读写 | 创建 | 是 |
| a | 只写 | 创建 | 追加 |
| a+ | 读写 | 创建 | 追加 |
readlines():获取所有行,返回list
verse_file = open('verse.txt','r',encoding="utf-8")
print(verse_file.readlines())
verse_file.close()
#result:
#['床前明月光\n', '疑是地上霜']
read():读取所有字符,返回string
verse_file = open('verse.txt','r',encoding="utf-8")
print(verse_file.read())
verse_file.close()
#result:
# 床前明月光
# 疑是地上霜
遍历文件最优法(懒加载)
verse_file = open('verse.txt','r',encoding="utf-8")
for row in verse_file:
print(row.strip())
#result:
# 床前明月光
# 疑是地上霜
write():写入.当mode为'w'[写]时,会清空之前的内容再写入;当mode为'a'[追加]时,会在原来基础上继续追加写入
verse_file = open('verse.txt','w',encoding="utf-8")
input_str = '举头望明月\n低头思故乡'
verse_file.write(input_str)
verse_file.close()
"""
verse.txt:
举头望明月
低头思故乡
"""
verse_file = open('verse.txt','a',encoding="utf-8")
input_str = '举头望明月\n低头思故乡'
verse_file.write(input_str)
verse_file.close()
"""
verse.txt:
床前明月光
疑是地上霜举头望明月
低头思故乡
"""
seek(position):定位光标位置
verse_file = open('verse.txt','r',encoding="utf-8")
verse_file.seek(6)#utf-8中一个中文字符占3个字节
print(verse_file.read())
verse_file.close()
"""
verse.txt:
明月光
疑是地上霜
"""
tell():获取光标位置
verse_file = open('verse.txt','r',encoding="utf-8")
verse_file.seek(6)
print(verse_file.tell());#result:6
练习
多级目录文件持久化增删改查

address.dic:
{}
file.py:
file = open('address.dic', 'r', encoding='utf8')
history_list = []
address_dic = eval(file.read())
while True:
print('---当前地址---')
for current in address_dic:
print(current)
choose = input('请选择---0:返回上一层,1:新增,2:删除,3:修改,4:查询,5:保存退出:')
':
if history_list:
address_dic = history_list.pop();
':
insert_name = input('请输入新增项名称:')
if insert_name in address_dic:
print('新增失败!该名称项已存在!')
continue;
else:
address_dic[insert_name] = {}
':
delete_name = input('请输入删除项名称:')
if delete_name not in address_dic:
print('删除失败!该名称项不存在!')
continue;
else:
del address_dic[delete_name];
':
modify_name = input('请输入修改项名称:')
if modify_name not in address_dic:
print('修改失败!该名称项不存在!')
continue;
else:
modify_to_name = input('请输入修改后的名称:')
modify_value = address_dic[modify_name];
address_dic[modify_to_name] = modify_value
del address_dic[modify_name]
':
select_name = input("请输入查询项名称:")
if select_name not in address_dic:
print('查询失败!该名称项不存在!')
continue;
else:
history_list.append(address_dic)
address_dic = address_dic[select_name]
if not address_dic:
print('当前无地址')
':
file = open('address.dic', 'w+', encoding='utf8')
if history_list:
file.write(str(history_list[0]))
else:
file.write(str(address_dic))
file.close();
break;
else:
print("输入错误")
运行结果:

address.dic:
{'湖北': {'武汉': {}}, '广东': {'深圳': {}}}
扩展
eval(str):可将对应格式字符串转成相应类型对象.例:
dic_str = "{'1':'a','2':'b'}"
list_str = "['1','2','3']"
dic = eval(dic_str)
list = eval(list_str)
print(dic,type(dic))
print(list,type(list))
#result:
# {'1': 'a', '2': 'b'} <class 'dict'>
# ['1', '2', '3'] <class 'list'>
with:类似C#中Using块,当前块执行完释放对象.下面两块代码等价.
with open("test",'r') as file:
file.read();
file = open("test",'r')
file.read()
file.close()
编码与解码
推荐博客:https://www.cnblogs.com/OldJack/p/6658779.html
python基础(5)-文件操作的更多相关文章
- python基础篇(文件操作)
Python基础篇(文件操作) 一.初始文件操作 使用python来读写文件是非常简单的操作. 我们使用open()函数来打开一个文件, 获取到文件句柄. 然后通过文件句柄就可以进行各种各样的操作了. ...
- python基础之文件操作
对于文件操作中最简单的操作就是使用print函数将文件输出到屏幕中,但是这种操作并不能是文件保存到磁盘中去,如果下调用该数据还的重新输入等. 而在python中提供了必要的函数和方法进行默认情况下的文 ...
- Day3 Python基础学习——文件操作、函数
一.文件操作 1.对文件操作流程 打开文件,得到文件句柄并赋值给一个变量 通过文件句柄对文件进行操作 关闭文件 #打开文件,读写文件,关闭文件 http://www.cnblogs.com/linha ...
- python基础14_文件操作
文件操作,通常是打开,读,写,追加等.主要涉及 编码 的问题. #!/usr/bin/env python # coding:utf-8 ## open实际上是从OS请求,得到文件句柄 f = ope ...
- 【python基础】文件操作
文件操作目录 一 .文件操作 二 .打开文件的模式 三 .操作文件的方法 四 .文件内光标移动 五. 文件的修改 一.文件操作介绍 计算机系统分为:计算机硬件,操作系统,应用程序三部分. 我们用pyt ...
- python基础4文件操作
在磁盘上读取文件的 功能都是由操作系统来实现的,不允许普通的程序直接操作磁盘,所以读写文件就是请求操作系统打开一个文件对象(通常称为文件描述符),然后,通过操作系统提供的接口从这个文件对象中读取数据( ...
- Python基础 之 文件操作
文件操作 一.路径 文件绝对路径:d:\python.txt 文件相对路径:在IDEA左边的文件夹中 二.编码方式 utf-8 gbk... 三.操作方式 1.只读 r 和 rb 绝对路径的打开操作 ...
- Python基础--基本文件操作
全部的编程语言都一样,学完了一些自带的数据机构后,就要操作文件了. 文件操作才是实战中的王道. 所以,今天就来分享一下Python中关于文件的一些基本操作. open方法 文件模式 这个模式对于写入文 ...
- python基础(10):文件操作
1. 初识文件操作 使⽤python来读写⽂件是非常简单的操作.我们使⽤open()函数来打开⼀个⽂件,获取到⽂ 件句柄,然后通过⽂件句柄就可以进⾏各种各样的操作了,根据打开⽅式的不同能够执⾏的操 作 ...
- Python基础学习——文件操作、函数
一.文件操作 文件操作链接:http://www.cnblogs.com/linhaifeng/articles/5984922.html(更多内容见此链接) 一.对文件操作流程 打开文件,得到文件句 ...
随机推荐
- linux下ls -l命令(即ll命令)查看文件的显示结果分析
在linux下使用“ls -l”或者“ls -al”或者“ll”命令查看文件及目录详情时,shell中会显示出好几列的信息.平时也没怎么注意过,今天忽然心血来潮想了解一下,于是整理了这篇博客,以供参考 ...
- python 读取大文件,按照字节读取
def read_bigFile(): f = open("123.dat",'r') cont = f.read() : print(cont) cont = f.read() ...
- Android WebRTC开发入门
在学习 WebRTC 的过程中,学习的一个基本步骤是先通过 JS 学习 WebRTC的整体流程,在熟悉了整体流程之后,再学习其它端如何使用 WebRTC 进行互联互通. 申请权限 Camera 权限 ...
- 简单的 FastDFS + Nginx 应用实例
版权声明:本文为GitChat作者的原创文章,未经 GitChat 同意不得转载. https://blog.csdn.net/GitChat/article/details/79479148 wx_ ...
- mysql数据字段整理
<?php header('content-type:text/html;charset=utf-8'); define('DB_HOST','127.0.01'); define('DB_US ...
- websocket采用tomcat方式,IOC类对象无法注入的解决方案
前言 我采用的spring框架做的,主要用于IOC AOP ,spring之前采用的2.0版本.(2.0版本出错!下面有解释): 要实现websocket 实现后台主动与JSP发送数据. 具体操作 在 ...
- java interface接口的传值方法
A 类 package interface_test; public class A { private IPresenter ip; public A(IPresenter ip) { this.i ...
- eclipse如何安裝JPA 和Data Source Explorer
安裝Data Source Explorer https://blog.csdn.net/XIAOZHI0999/article/details/61199801?utm_source=blogxgw ...
- linq2db sqlite应用
使用linq2db sqlite 的时候,找不到增加,删除的操作,原来是要引入一个新的命名空间LinqTODB. 1 using LinqToDB; 插入: 1 User uNew = new Use ...
- VS2017 配置QT5
QT安装 1. QT下载 2. 安装过程中,组件的选择(图自https://blog.csdn.net/gaojixu/article/details/82185694) 3. 安装完成 VS2017 ...