今天的主要内容是:

文件操作

对文件操作的流程:

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

现有文件如下:

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. struts2.5.2 通配符问题_亲测有用

    学了一段时间struts2,跟着教程做,但发现struts2的版本不同,很多东西的使用是有差异的.例如之前遇到的创建sessionFactory的方式就跟之前版本有着明显的差异.今天又遇到一个问题,那 ...

  2. C# SetWindowsHookEx

    [DllImport("user32.dll")] static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookPr ...

  3. eclipse的任务列表

    如上图所示,备注加  TODO  ,可以在tasks列表中显示,提示你还有哪些工作需要完善 昨天遇到一个问题,加了  TODO  任务列表里却不显示,后来发现是因为任务列表只显示了前100条,而我的项 ...

  4. MIUI 的参与感

    最近这段时间在看小米联合创始人黎万强写的<参与感>这本书,看完我还挺有感触的.小米相信大家都一定有所耳闻. 2010 年 4 月 6 日            小米公司正式创立. 8 月 ...

  5. Oracle query that count connections by minute with start and end times provided

    数据结构类似 SQL> select * from t; B                 E                 N ----------------- ------------ ...

  6. Qt Creator 中文乱码问题

    一. Qt 4 乱码问题 解决方案 1. 在Qt 中 快捷菜单选项功能中 Edit(编辑)  --> Select Encoding...(选择编码) 选择载入(显示)编码和储存编码,要解决中文 ...

  7. [luogu3155 CQOI2009] 叶子的染色(树形dp)

    传送门 Solution 十分简单的树形dpQwQ,转移关系:父亲染了儿子不用染 只需要确定根就是简单树形dp,而其实根可以随便取一个非叶子节点 可以分情况讨论发现答案并不会改变 Code //By ...

  8. 原来PHP对象比数组用更少的内存

    一直以为php的数组更节省内存,从来没有测试过,今天因为要读取一个大配置文件作为pool.做了一次测试: 得出结论是 使用对象保存数据更好,花费的内存是数组array的1/4. 测试代码 class ...

  9. .Net防sql注入的方法总结

    #防sql注入的常用方法: 1.服务端对前端传过来的参数值进行类型验证: 2.服务端执行sql,使用参数化传值,而不要使用sql字符串拼接: 3.服务端对前端传过来的数据进行sql关键词过来与检测: ...

  10. 【codeforces 755F】PolandBall and Gifts

    [题目链接]:http://codeforces.com/contest/755/problem/F [题意] n个人; 计划是每个人都拿一个礼物来送给一个除了自己之外的人; 且如果一个人没有送出礼物 ...