文件操作
读写操作都在内存中,只有在close后才会保存到文件
r = open('江雪.txt','r',encoding='utf-8')
r.fileno()#返回文件描述符。中文返回3
r.flush()#操作完即保存到文件中,
r.close()
r.read()#单位为字符,可指定数量,默认全部读取
r.readline()#默认一行
r.readlines()#默认剩余所有内容,显示为一个列表
r.seek()#将光标移动到指定位置
r.tell()#查看当前光标的位置
r.truncate()#截断,
r.write()
r ,只读模式【默认】
w,只写模式【不可读;不存在则创建;存在则清空内容;】
x, 只写模式【不可读;不存在则创建,存在则报错】
a, 追加模式【可读; 不存在则创建;存在则只追加内容;】
"+" 表示可以同时读写某个文件
r+, 读写【可读,可写】 w+,写读【可读,可写】 x+ ,写读【可读,可写】 a+, 写读【可读,可写】 "b"表示以字节的方式操作
rb 或 r+b wb 或 w+b xb 或 w+b ab 或 a+b
注:以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型
r+:读管自己读,写的话,从最后开始写
w+:首先就是清空,write之后进行read,但是read是从write的光标位置开始读
a+:光标开始就是最后,和r+的区别只是初始光标位置
无法直接修改原文件,只能通过创建新文件,进行修改和添加
with open('江雪.txt','r',encoding='utf-8') as r:#功能同上,只是退出with时,自动close
在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
withopen('log1') as obj1,open('log2') as obj2:
r = open('江雪.txt','r',encoding='utf-8')
# for i in r.readlines():错误姿势,可以执行,但会一次性把所有的东西取到内存中
for i in r:#正确的姿势:for内部将r这个文件对象做成一个迭代器,用一行去一行。
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 readline(self, *args, **kwargs):pass
def readlines(self, *args, **kwargs):pass
def tell(self, *args, **kwargs): #real signature unknown
"""Current file position.
Can raise OSError for non seekable files."""
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 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
def flush(self, *args, **kwargs):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 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
##############################################################less usefull
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 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 seekable(self, *args, **kwargs): #real signature unknown
"""True if file supports random-access."""
pass
def writable(self, *args, **kwargs): #real signature unknown
"""True if file was opened in a write mode."""
pass操作方法介绍
操作方法介绍
classTextIOWrapper(_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)."""
passbuffer= 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
文件操作3.x
classfile(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()."""
return0def 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."""
returnFalsedef 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 >= 0); other values are 1
(move relative to current position, positive or negative), and 2 (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
2.x
文件操作2.x
使用Python内置的open()函数,打开一个文件对象,在磁盘中读写str、bytes
StringIO顾名思义就是在内存中读写str
BytesIO实现了在内存中读写bytes
我们把变量从内存中变成可存储或传输的过程称之为序列化
序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。
参考:https://www.cnblogs.com/yuanchenqi/articles/5782764.html
循环
if 条件1:
自拍
elif 条件2:
蹦
else:
跳舞
continue 结束本次循环,继续下一次循环
break 跳出整个当前的循环(只能跳出一层)
If elif else 只执行其中一个
但while else;for else执行循环后,才执行else
for循环
while循环