python修炼6
一、文件操作
1
|
文件句柄 = open ( '文件路径' , '模式' ) |
打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。
打开文件的模式有:
- r ,只读模式【默认】
- w,只写模式【不可读;不存在则创建;存在则清空内容】
- x, 只写模式【不可读;不存在则创建,存在则报错】
- a, 追加模式【不可读;不存在则创建;存在则只追加内容】
"+" 表示可以同时读写某个文件
- r+, 读写【可读,可写】
- w+,写读【可读,可写】
- x+ ,写读【可读,可写】
- a+, 写读【可读,可写】
"b"表示以字节的方式操作
- rb 或 r+b
- wb 或 w+b
- xb 或 w+b
- ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
二、操作
####### r 读 #######
f = open('test.log','r',encoding='utf-8')
a = f.read()
print(a) ###### w 写(会先清空!!!) ######
f = open('test.log','w',encoding='utf-8')
a = f.write('car.\n索宁')
print(a) #返回字符 ####### a 追加(指针会先移动到最后) ########
f = open('test.log','a',encoding='utf-8')
a = f.write('girl\n索宁')
print(a) #返回字符 ####### 读写 r+ ########
f = open('test.log','r+',encoding='utf-8')
a = f.read()
print(a)
f.write('nick') ##### 写读 w+(会先清空!!!) ######
f = open('test.log','w+',encoding='utf-8')
a = f.read()
print(a)
f.write('jenny') ######## 写读 a+(指针先移到最后) #########
f = open('test.log','a+',encoding='utf-8')
f.seek() #指针位置调为0
a = f.read()
print(a)
b = f.write('nick')
print(b) ####### rb #########
f = open('test.log','rb')
a = f.read()
print(str(a,encoding='utf-8')) # ######## ab #########
f = open('test.log','ab')
f.write(bytes('索宁\ncar',encoding='utf-8'))
f.write(b'jenny') ##### 关闭文件 ######
f.close() ##### 内存刷到硬盘 #####
f.flush() ##### 获取指针位置 #####
f.tell() ##### 指定文件中指针位置 #####
f.seek() ###### 读取全部内容(如果设置了size,就读取size字节) ######
f.read()
f.read() ###### 读取一行 #####
f.readline() ##### 读到的每一行内容作为列表的一个元素 #####
f.readlines()
class file(object)
def close(self): # real signature unknown; restored from __doc__
关闭文件
"""
close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for
further I/O operations. close() may be called more than once without
error. Some kinds of file objects (for example, opened by popen())
may return an exit status upon closing.
""" def fileno(self): # real signature unknown; restored from __doc__
文件描述符
"""
fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read().
"""
return def flush(self): # real signature unknown; restored from __doc__
刷新文件内部缓冲区
""" flush() -> None. Flush the internal I/O buffer. """
pass def isatty(self): # real signature unknown; restored from __doc__
判断文件是否是同意tty设备
""" isatty() -> true or false. True if the file is connected to a tty device. """
return False def next(self): # real signature unknown; restored from __doc__
获取下一行数据,不存在,则报错
""" x.next() -> the next value, or raise StopIteration """
pass def read(self, size=None): # real signature unknown; restored from __doc__
读取指定字节数据
"""
read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached.
Notice that when in non-blocking mode, less data than what was requested
may be returned, even if no size parameter was given.
"""
pass def readinto(self): # real signature unknown; restored from __doc__
读取到缓冲区,不要用,将被遗弃
""" readinto() -> Undocumented. Don't use this; it may go away. """
pass def readline(self, size=None): # real signature unknown; restored from __doc__
仅读取一行数据
"""
readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum
number of bytes to return (an incomplete line may be returned then).
Return an empty string at EOF.
"""
pass def readlines(self, size=None): # real signature unknown; restored from __doc__
读取所有数据,并根据换行保存值列表
"""
readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read.
The optional size argument, if given, is an approximate bound on the
total number of bytes in the lines returned.
"""
return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
指定文件中指针位置
"""
seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to
(offset from start of file, offset should be >= ); other values are
(move relative to current position, positive or negative), and (move
relative to end of file, usually negative, although many platforms allow
seeking beyond the end of a file). If the file is opened in text mode,
only offsets returned by tell() are legal. Use of other offsets causes
undefined behavior.
Note that not all file objects are seekable.
"""
pass def tell(self): # real signature unknown; restored from __doc__
获取当前指针位置
""" tell() -> current file position, an integer (may be a long integer). """
pass def truncate(self, size=None): # real signature unknown; restored from __doc__
截断数据,仅保留指定之前数据
"""
truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell().
"""
pass def write(self, p_str): # real signature unknown; restored from __doc__
写内容
"""
write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.
"""
pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
将一个字符串列表写入文件
"""
writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object
producing strings. This is equivalent to calling write() for each string.
"""
pass def xreadlines(self): # real signature unknown; restored from __doc__
可用于逐行读取文件,非全部
"""
xreadlines() -> returns self. For backward compatibility. File objects now include the performance
optimizations previously implemented in the xreadlines module.
"""
pass .x
2.0文档
class TextIOWrapper(_TextIOBase):
"""
Character and line based layer over a BufferedIOBase object, buffer. encoding gives the name of the encoding that the stream will be
decoded or encoded with. It defaults to locale.getpreferredencoding(False). errors determines the strictness of encoding and decoding (see
help(codecs.Codec) or the documentation for codecs.register) and
defaults to "strict". newline controls how line endings are handled. It can be None, '',
'\n', '\r', and '\r\n'. It works as follows: * On input, if newline is None, universal newlines mode is
enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
these are translated into '\n' before being returned to the
caller. If it is '', universal newline mode is enabled, but line
endings are returned to the caller untranslated. If it has any of
the other legal values, input lines are only terminated by the given
string, and the line ending is returned to the caller untranslated. * On output, if newline is None, any '\n' characters written are
translated to the system default line separator, os.linesep. If
newline is '' or '\n', no translation takes place. If newline is any
of the other legal values, any '\n' characters written are translated
to the given string. If line_buffering is True, a call to flush is implied when a call to
write contains a newline character.
"""
def close(self, *args, **kwargs): # real signature unknown
关闭文件
pass def fileno(self, *args, **kwargs): # real signature unknown
文件描述符
pass def flush(self, *args, **kwargs): # real signature unknown
刷新文件内部缓冲区
pass def isatty(self, *args, **kwargs): # real signature unknown
判断文件是否是同意tty设备
pass def read(self, *args, **kwargs): # real signature unknown
读取指定字节数据
pass def readable(self, *args, **kwargs): # real signature unknown
是否可读
pass def readline(self, *args, **kwargs): # real signature unknown
仅读取一行数据
pass def seek(self, *args, **kwargs): # real signature unknown
指定文件中指针位置
pass def seekable(self, *args, **kwargs): # real signature unknown
指针是否可操作
pass def tell(self, *args, **kwargs): # real signature unknown
获取指针位置
pass def truncate(self, *args, **kwargs): # real signature unknown
截断数据,仅保留指定之前数据
pass def writable(self, *args, **kwargs): # real signature unknown
是否可写
pass def write(self, *args, **kwargs): # real signature unknown
写内容
pass def __getstate__(self, *args, **kwargs): # real signature unknown
pass def __init__(self, *args, **kwargs): # real signature unknown
pass @staticmethod # known case of __new__
def __new__(*args, **kwargs): # real signature unknown
""" Create and return a new object. See help(type) for accurate signature. """
pass def __next__(self, *args, **kwargs): # real signature unknown
""" Implement next(self). """
pass def __repr__(self, *args, **kwargs): # real signature unknown
""" Return repr(self). """
pass buffer = property(lambda self: object(), lambda self, v: None, lambda self: None) # default closed = property(lambda self: object(), lambda self, v: None, lambda self: None) # default encoding = property(lambda self: object(), lambda self, v: None, lambda self: None) # default errors = property(lambda self: object(), lambda self, v: None, lambda self: None) # default line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None) # default name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default newlines = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None) # default _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None) # default .x
3.0文档
三、管理上下文
为了避免打开文件后忘记关闭,可以通过管理上下文,即:
1
2
3
|
with open ( 'log' , 'r' ) as f: ... |
如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
在Python 2.7 及以后,with又支持同时对多个文件的上下文进行管理,即:
1
2
|
with open ( 'log1' ) as obj1, open ( 'log2' ) as obj2: pass |
1
2
3
4
5
|
###### 从一文件挨行读取并写入二文件 ######### with open ( 'test.log' , 'r' ) as obj1 , open ( 'test1.log' , 'w' ) as obj2: for line in obj1: obj2.write(line) |
基础目录
python修炼6的更多相关文章
- python修炼第一天
Python修炼第一天 新的开始:不会Python的运维,人生是不完整的. 为了我的人生能够完整,所以我来了!今后跟着太白金星师傅学习功夫,记录一下心得,以便日后苦练. 一 Python的历史: Py ...
- Python 修炼1
2016年11月21日 Python基础修炼第一篇 1.Python是什么?有什么优缺点呢? python是一个高级编程语言. 优点:开发效率比较高,不但有php写网页的功能,还有写后台的功能 缺点: ...
- Python修炼10------面向对象
面向对象-----类 类:类是一种数据结构,就好比一个模型,该模型用来表述一类事物(事物即数据和动作的结合体),用它来生产真实的物体(实例). 对象:什么叫对象:睁开眼,你看到的一切的事物都是一个个的 ...
- python修炼7----迭代器
迭代器 -------------------------------------------------------------------------------- 充电小知识 1.yield-- ...
- Python 修炼3
# 列表 功能方法 *补充(zip zip(list1,list2) 会形成一个[(),()]新的列表list1和list2一一对应得组成一个新的元素以元组最为单位) # 1.修改# li = [1, ...
- Python 修炼2
Python开发IDE:Pycharm.elipse 1.运算符 1 1.算数运算 + - * / // ** % 2. 赋值运算 a = 1 a += 2 3.比较运算 1>3 4.逻辑运算 ...
- python修炼第七天
第七天面向对象进阶,面向对象编程理解还是有些难度的,但是我觉得如果弄明白了,要比函数编程过程编程省事多了.继续努力! 1.面向对象补充: 封装 广义上的封装:把变量和函数都放在类中狭义上的封装:把一些 ...
- python修炼第六天
越来越难了....现在啥也不想说了,撸起袖子干. 1 面向对象 先来个例子: 比如人狗大战需要有狗,人所以创建两个类别模子def Person(name,sex,hp,dps): dic = {&qu ...
- python修炼第五天
第五天,感觉开始烧脑了.递归逻辑难,模块数量多,但是绝世武功都是十年磨一剑出来的!稳住! 1 递归. 定义-----递归就是在函数的内部调用自己递归深度 998不建议修改递归深度,因为如果998都没有 ...
随机推荐
- tastypie Django REST framework
Its one of the primary authors' lecture on pyCon: http://www.youtube.com/watch?v=Zv26xHYlc8s&nor ...
- 使用ResourceDictionary管理Logical Resources
WPF整理-使用ResourceDictionary管理Logical Resources “Logical resources may be of various types, such as br ...
- transaction manager has disabled its support for remote/network transactions. 该伙伴事务管理器已经禁止了它对远程/网络事务
最近再用SSIS做数据归档,里面用到了分布式事务.在开发阶段是在一台计算机上运行只要是启动分布式服务就没什么问题,可是昨天把它部署到uat的时候遇到问题,错误信息是: 最后找到解决方案: 确认&quo ...
- Python pandas 0.19.1 Intro to Data Structures 数据结构介绍 文档翻译
官方文档链接http://pandas.pydata.org/pandas-docs/stable/dsintro.html 数据结构介绍 我们将以一个快速的.非全面的pandas的基础数据结构概述来 ...
- 【转】HTTP Response Header 的 Content-Disposition
因为听到有同事讨论JSP输出Excel文件的,就是在页面上有一个[导出]按钮,能够将查询结果导出到Excel文件让用户下载.有人说要用POI在后台生成临时的Excel文件,然后通过读取FileStre ...
- ICSharpCode.TextEditor如何自定义代码折叠和高亮
ICSharpCode.TextEditor 是一款非常不错的.NET代码编辑控件,内置了多种高亮语言支持,同时完美支持中文,非常赞!先来看一下运行效果: 1 项目结构 这里需要注意lib文件夹下导入 ...
- 详述JavaScript数组
摘要 数组是JavaScript中的常用类型,本文详述了数组的基本知识以及一些常用的数组方法,并对每种方法进行了详细解释 数组定义 用字面量直接定义 var arr=[0,0,0]; //注意,是方括 ...
- js面向对象小结(工厂模式,构造函数,原型方法,继承)
最近过了一遍尼古拉斯泽卡斯的高级程序设计第三版(红皮书)第六章:面向对象程序设计,现在把总结出来的东西和大家分享一下. 主要内容如下: 1.工厂模式 2.构造函数模式 3.原型模式 4.继承 一.工厂 ...
- web页面在微信里打开,字体颜色不正常显示
问题:写的web项目在微信里的webview里打开(iphone手机),会出现颜色的不识别.写的是白色,数字的部分会过了3-5秒后,变成黑色! 原因:在iphone手机里,数字的部分(具体的长度没有测 ...
- java的return区别
return ;和return null的区别在于:前者当方法返回值为void时候,return ; 跳出方法. 后者当方法的返回值为object对象时,return null,跳出方法,返回值为空值 ...