浅谈自学Python之路(day3)
今天的主要内容是:
- 撒
文件操作
对文件操作的流程:
- 打开文件,得到文件句柄并赋值给一个变量
- 通过句柄对文件进行操作
- 关闭文件
现有文件如下:
tonghuazhen
听说白雪公主在逃跑
小红帽在担心大灰狼
听说疯帽喜欢爱丽丝
丑小鸭会变成白天鹅
听说彼得潘总长不大
杰克他有竖琴和魔法
听说森林里有糖果屋
灰姑娘丢了心爱的玻璃鞋
只有睿智的河水知道
白雪是因为贪玩跑出了城堡
小红帽有件抑制自己
变成狼的大红袍
总有一条蜿蜒在童话镇里七彩的河
沾染魔法的乖张气息
却又在爱里曲折
川流不息扬起水花
又卷入一帘时光入水
让所有很久很久以前
都走到幸福结局的时刻
打开文件的模式有:
- r,只读模式(默认)。
- w,只写模式。【不可读;不存在则创建;存在则删除内容;】
- a,追加模式。【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
- r+,可读写文件。【可读;可写;可追加】
- w+,写读
- a+,同a
"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)
- rb
- wb
- ab
知道了以上的模式后,现在就来进入我们的操作:
- read:读
f = open("yesterday","r",encoding="utf-8")#文件句柄 [文件名/操作首字母/字符编码]
#r = read 读
data = f.read()
print(data)
f.close()
- write:写
f = open("yesterday","w",encoding="utf-8")#文件句柄 [文件名/操作首字母/字符编码]
#w = write 写 重新创建新文档,如果文档名称有重复则覆盖原文档
f.write("\n人心无可填\n")
f.write("河水太浅,怎托得起,岁月的积淀")
f.close()
- append:追加
f = open("yesterday2","a",encoding="utf-8")#文件句柄 [文件名/操作首字母/字符编码]
#a = append 追加 只能追加,不能读
f.write("\n人心无可填......\n")
f.write("河水太浅,怎托得起,岁月的积淀........")
f.close()
- 读前五行代码:
f = open("yesterday","r",encoding="utf-8")#文件句柄 [文件名/操作首字母/字符编码]
#读前五行
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
print(f.readline())
- 用循环写前五行代码:
#读前五行
for i in range(5):
print(f.readline())
- 将其变为列表格式输出:
print(f.readlines())#变为列表,每一行是一个元素
输出结果为:

这就是列表的格式
- 如果用循环输出这个列表:
#循环列表
for line in f.readlines():
print(line.strip())# .strip()空格和换行都去掉
这里用到了Python strip()方法:
描述
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格)。
语法
strip()方法语法:
str.strip([chars]);
- 打印文档中的前十行:
#打印前10行 , f.readlines()只适合读小文件
for index,line in enumerate(f.readlines()):
if index == 9:
print("这是一条分割线".center(50,"-"))
continue
print(line.strip())
但这方法只适合打印小文件,如果数据较大我们用下面这种方法:
count = 0
for line in f:
if count == 9:
print("---分割线---")
count += 1
continue
print(line)
count += 1
输出结果为:

其它语法:
def close(self): # real signature unknown; restored from __doc__
"""
Close the file. A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全读回来
Read at most size bytes, returned as bytes. Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return "" def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes. In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,没人知道它是干嘛用的 def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position. Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file). Note that not all file objects are seekable.
"""
pass def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position. Can raise OSError for non seekable files.
"""
pass def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size. Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written. Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass
浅谈自学Python之路(day3)的更多相关文章
- 浅谈自学Python之路(day2)
今天的主要内容是: 标准库 数据类型知识 数据运算 三元运算 bytes类型 字符串操作 字典 集合 标准库 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有 ...
- 浅谈自学Python之路(购物车程序练习)
购物车程序练习 今天我们来做一个购物车的程序联系,首先要理清思路 购物车程序需要用到什么知识点 需要用到哪些循环 程序编写过程中考虑值的类型,是int型还是字符串 如果值为字符串该怎么转成int型 用 ...
- 浅谈自学Python之路(day1)
2018-02-19 17:15:14 Python语言相对于其他语言较为简洁,也相对好入门比如后面不加分号,基本见不着大括号等优点 第一个程序,也是学每门语言都需要掌握的第一个代码 print(& ...
- 自学Python之路
自学Python之路[第一回]:初识Python 1.1 自学Python1.1-简介 1.2 自学Python1.2-环境的搭建:Pycharm及python安装详细教程 1.3 ...
- 自学Python之路-Python核心编程
自学Python之路-Python核心编程 自学Python之路[第六回]:Python模块 6.1 自学Python6.1-模块简介 6.2 自学Python6.2-类.模块.包 ...
- 自学Python之路-Python基础+模块+面向对象+函数
自学Python之路-Python基础+模块+面向对象+函数 自学Python之路[第一回]:初识Python 1.1 自学Python1.1-简介 1.2 自学Python1.2-环境的 ...
- 自学Python之路-django
自学Python之路-django 自学Python之路[第一回]:1.11.2 1.3
- 自学Python之路-Python并发编程+数据库+前端
自学Python之路-Python并发编程+数据库+前端 自学Python之路[第一回]:1.11.2 1.3
- 自学Python之路-Python网络编程
自学Python之路-Python网络编程 自学Python之路[第一回]:1.11.2 1.3
随机推荐
- PHP 之phpqrcode类库生成二维码
<?php /** * Created by PhpStorm. * User: 25754 * Date: 2019/6/4 * Time: 15:53 */ include "./ ...
- centos 7 配置nginx
安装nginx: curl -o nginx.rpm http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0. ...
- Java字符字符串类
Java字符字符串类 Character 类 Character 类用于对单个字符进行操作.Character 类在对象中包装一个基本类型 char 的值在实际开发过程中,我们经常会遇到需要使用对象, ...
- Django - ORM实现用户登陆
1.路由分发cmdb(app)下urls.py中,建立url与函数对应关系 2.login.html代码: 3.views.py中,login函数,确认是否登陆成功 备注:从前端 获取用户名,密码,在 ...
- 1 WebService 常见问题
<binding name="> <readerQuotas maxStringContentLength=" /> </binding> &l ...
- codevs1961 躲避大龙
1961 躲避大龙 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 钻石 Diamond 题解 题目描述 Description 你早上起来,慢悠悠地来到学校门口, ...
- 三、Scrapy中选择器用法
官方示例源码<html> <head> <base href='http://example.com/' /> <title>Example web ...
- 34.分组聚合操作—bucket
主要知识点: 学习聚合知识 一.准备数据 1.家电卖场案例背景建立index 以一个家电卖场中的电视销售数据为背景,来对各种品牌,各种颜色的电视的销量和销售额,进行各种各样角度的分析 ...
- Silverlight之我见——数据批示(1)
第一次听到这个概念,你是否有点陌生?MSDN上也没有特意的去说明.不要看到这个名词不太熟悉,其实数据批示,玩过C#的人都会非常熟悉,所谓数据批示,其本质就是特性(Attribute),怎么样,现在有点 ...
- GlobalSign 多域型(SNAs) SSL 证书
GlobalSign 多域型(SNAs) SSL 证书 GlobalSign 多域型(SNAs) SSL 证书,有别于通配符 SSL 证书可以同时保护一个域名下所有的子域名网站,SANs 证书更进一步 ...