今天的主要内容是:

文件操作

对文件操作的流程:

  • 打开文件,得到文件句柄并赋值给一个变量
  • 通过句柄对文件进行操作
  • 关闭文件

现有文件如下:

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)的更多相关文章

  1. 浅谈自学Python之路(day2)

    今天的主要内容是: 标准库 数据类型知识 数据运算 三元运算 bytes类型 字符串操作 字典 集合 标准库 Python的强大之处在于他有非常丰富和强大的标准库和第三方库,几乎你想实现的任何功能都有 ...

  2. 浅谈自学Python之路(购物车程序练习)

    购物车程序练习 今天我们来做一个购物车的程序联系,首先要理清思路 购物车程序需要用到什么知识点 需要用到哪些循环 程序编写过程中考虑值的类型,是int型还是字符串 如果值为字符串该怎么转成int型 用 ...

  3. 浅谈自学Python之路(day1)

    2018-02-19  17:15:14 Python语言相对于其他语言较为简洁,也相对好入门比如后面不加分号,基本见不着大括号等优点 第一个程序,也是学每门语言都需要掌握的第一个代码 print(& ...

  4. 自学Python之路

    自学Python之路[第一回]:初识Python    1.1 自学Python1.1-简介    1.2 自学Python1.2-环境的搭建:Pycharm及python安装详细教程    1.3  ...

  5. 自学Python之路-Python核心编程

    自学Python之路-Python核心编程 自学Python之路[第六回]:Python模块       6.1 自学Python6.1-模块简介    6.2 自学Python6.2-类.模块.包  ...

  6. 自学Python之路-Python基础+模块+面向对象+函数

    自学Python之路-Python基础+模块+面向对象+函数 自学Python之路[第一回]:初识Python    1.1 自学Python1.1-简介    1.2 自学Python1.2-环境的 ...

  7. 自学Python之路-django

    自学Python之路-django 自学Python之路[第一回]:1.11.2 1.3

  8. 自学Python之路-Python并发编程+数据库+前端

    自学Python之路-Python并发编程+数据库+前端 自学Python之路[第一回]:1.11.2 1.3

  9. 自学Python之路-Python网络编程

    自学Python之路-Python网络编程 自学Python之路[第一回]:1.11.2 1.3

随机推荐

  1. python_文件io

    # -*- coding:UTF-8 -*-#从键盘读入raw_input([prompt]) #函数从标准输入读取一个行,并返回一个字符串(去掉结尾的换行符)#input([prompt]) 函数和 ...

  2. 如何知道自己的CPU支持SLAT

    因为WP8 SDK发布,很多WP8的开发者们也开始陆续安装WP8的SDK的,然而安装WP8的SDK有很多软件和硬件的要求,其中有一个就是——要求CPU支持二级地址转换(SLAT),如果CPU不支持二级 ...

  3. Java单元测试 - TestNG

    官网 Eclipse安装TestNG插件 与Junit相比 从Junit发展而来,开发者就是Junit小组的一个人 Test Suite不再需要硬编码,就像cf自动登录的脚本中一样,可以写到一个xml ...

  4. 扩增子图表解读5火山图:差异OTU的数量及变化规律

    火山图 Volcano plot 在统计学上,火山图是一种类型的散点图,被用于在大数据中快速鉴定变化.由于它的形成像火山喷发的样子,所以被称为火山图.和上文讲的曼哈顿图类似.   火山图基本元素 火山 ...

  5. CorelDRAW快速制作抖音幻影图像效果

    本教程讲解非常受欢迎的幻影图像效果(Anaglyph 3d),也叫图像分色立体效果,这其中我们要用到CorelDRAW中的透明度工具. 在开始实施Anaglyph效应之前,应当知道,Anaglyph  ...

  6. UpdateData

    UpdateData 类似于C语言的scanf printf函数 管理控件与关联变量之间的数据更新. updatedata(true)把界面输入的数值更新到关联变量中,updatedata(false ...

  7. 获取webconfig配置文件内容

    string ServerUrl= ConfigurationManager.AppSettings["ServerUrl"].ToString(); web.config中的配置 ...

  8. 【Apache Kafka】一、Kafka简介及其基本原理

      对于大数据,我们要考虑的问题有很多,首先海量数据如何收集(如Flume),然后对于收集到的数据如何存储(典型的分布式文件系统HDFS.分布式数据库HBase.NoSQL数据库Redis),其次存储 ...

  9. Quartz.NET 定时任务使用

    class Program { static void Main(string[] args) { StartJob(); Console.ReadKey(); } static void Start ...

  10. proxy 跨域配置, 针对有axios的baseURL

    1.首先主要的config文件下的index.js中的proxytable配置 proxyTable:{ '/proxy': { target:'http://192.168.2.141:8080', ...