今天的主要内容是:

文件操作

对文件操作的流程:

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

现有文件如下:

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

最新文章

  1. centos 网络配置
  2. windows服务器。linux服务器的集成包推荐
  3. MongoDB的启动
  4. asp.net连接oracle的问题及方法总结
  5. Ext4 简单的treepanel
  6. C++ 通过Thunk在WNDPROC中访问this指针实现细节
  7. Java消息服务
  8. 每天一个Linux命令(09)--touch命令
  9. Octopus——excel导入导出工具
  10. luogu1001 A+B Problem
  11. Lua Table转C# Dictionary
  12. xamarin.forms之使用CarouselView插件模仿网易新闻导航
  13. Linux Crontab Shell脚本实现秒级定时任务
  14. Spring框架学习01——使用IDEA开发Spring程序
  15. 如何搭建 LNMP环境
  16. 再次谈谈easyui datagrid 的数据加载
  17. Struts2 Validate
  18. 字体相关CSS属性介绍
  19. c# string与String区别
  20. Vmware+CentOs7+共享目录

热门文章

  1. (转)OL2中设置鼠标的样式
  2. 关于 实体类中 时间字段 为string 类型和 datatime类型 比较
  3. 《C++ Primer 第5版》第1章
  4. flutter 环境搭建
  5. Luogu P1256 显示图像
  6. 新版本的molar mass(uva-1586)明明debug过了,各种测试还是WA真是气死我了
  7. linux下root用户和tarena用户vimrc配置
  8. Silverlight之我见——数据批示(1)
  9. 第八节:numpy之四则运算与逻辑运算
  10. 【codeforces 508B】Anton and currency you all know