今天的主要内容是:

文件操作

对文件操作的流程:

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

现有文件如下:

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. (转)Hibernate框架基础——cascade属性

    http://blog.csdn.net/yerenyuan_pku/article/details/52760010 我们以部门和员工的关系为例讲解一对多关联关系映射时,删除部门时,如果部门有关联的 ...

  2. CAD插入jpg

    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 3 ...

  3. 洛谷——P2814 家谱

    P2814 家谱 题目背景 现代的人对于本家族血统越来越感兴趣. 题目描述 给出充足的父子关系,请你编写程序找到某个人的最早的祖先. 输入输出格式 输入格式: 输入由多行组成,首先是一系列有关父子关系 ...

  4. linux下root用户和tarena用户vimrc配置

    设置vim自动缩进,行号,tab键宽度 如果是root超级用户,他的主目录是: /root ,打开文件vim的配置文件.vimrc 如果是tarena用户,他的主目录是:/home/tarena 打开 ...

  5. Mysql 模糊查询总结

    语法: SELECT 字段集 FROM 表名 WHERE 字段名 LIKE 条件 模糊查询有四种匹配模式: 1.%:匹配任意0个或多个字符. 2._:匹配任意1个字符. 3.[]:匹配括号内所列字符中 ...

  6. 8.1.3 Row对象

    假设数据以下面的方式创建并插入数据: import sqlite3 conn = sqlite3.connect(r'D:\test.db') c = conn.cursor() c.execute( ...

  7. Windows读取NXP MiFare Ultralight C类型NFC卡片的信息

    1,读取 我们需要外接一个NFC Reader让Windows可以读取NFC卡片的内容. 因为特殊原因,我们选择了Sony rc-s380 NFC Reader.相关介绍 我们需要下载并安装NFC P ...

  8. poj 1724 最短路+优先队列(两个约束条件)

    /*两个约束条件求最短路,用优先队列*/ #include<stdio.h> #include<string.h> #include<queue> using na ...

  9. WGS84坐标系图层转火星坐标系(是整个图层转哟,不是转单点坐标)

    开篇唠叨(着急的略过) 大天朝“火星坐标系”小科普:是一种国家保密插件,对真实坐标系统进行人为的加偏处理,将真实的坐标加密成虚假的坐标,加密后的坐标被称为火星坐标系统.所有的电子地图所有的导航设备,都 ...

  10. [LeetCode]Valid Sudoku解题记录

    这道题考查对二维数组的处理,哈希表. 1.最自然的方法就是分别看每一个数是否符合三个规则.所以就须要对应的数据结构来 记录这些信息,判定是否存在.显然最先想到用哈希表. 2.学会把问题抽象成一个个的子 ...