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都没有 ...
随机推荐
- 【Win32API】SendInput ERROR_BUSY 错误原因
最近需要解决一个Windows上模拟键盘输入的问题, 使用SendInput这个API来实现的.当我从另外一台机器给当前机器发送一条键盘指令时,发现SendInput一直是成功的,但是没有看到任何输入 ...
- [每日一题] OCP1z0-047 :2013-07-16 主键与唯一索引
主键包括非空和唯一约束,它会自动创建唯一索引(注:唯一约束也会自动创建唯一索引),测试如下: 1. 创建一个表products gyj@OCM> Create table products( 2 ...
- 百度地图在某架构下找不到符号.a文件的问题
1.现象: 就是说找不到符号给i386的架构(就是模拟器).或者找不到符号给arm架构(真机). ld: warning: ignoring file /Users/pufang/xcode/demo ...
- install cuda5 on ubuntu12.04
1. sudo apt-get install libglapi-mesa 2. sudo apt-get install freeglut3-dev build-essential libx11-d ...
- Android——另外一种增删查改的方式(ContentProvider常用)
以下介绍另外一种增删查改的方式 package com.njupt.sqllist; import java.util.ArrayList; import java.util.List; import ...
- javaapplicationWeb application setup on Ubuntu VPS
题记:写这篇博客要主是加深自己对javaapplication的认识和总结实现算法时的一些验经和训教,如果有错误请指出,万分感谢. Now there are many hosting server ...
- webpack入门必知必会
关于 微信公众号:前端呼啦圈(Love-FED) 我的博客:劳卜的博客 知乎专栏:前端呼啦圈 前言 这是我第一篇介绍webpack的文章,先从一个入门教程开始吧,后续会有更多相关webpack的文章推 ...
- CSS倒影
前面的话 CSS倒影目前只有chrome和safari浏览器支持,且需要添加-webkit-前缀.本文将详细介绍CSS倒影box-reflect 语法 -webkit-box-reflect 初始 ...
- JMS ActiveMQ案例
创建一个web工程 导入ActiveMQ依赖的jar包 activemq-all-5.9.jar 写一个生产者(send)servlet package com.sun.jms;import jav ...
- git commit
使用 git add 命令将想要快照的内容写入缓存区, 而执行 git commit 将缓存区内容添加到仓库中. Git 为你的每一个提交都记录你的名字与电子邮箱地址,所以第一步需要配置用户名和邮箱地 ...