python 循环写文件_python-文件操作及循环
文件操作
讀寫(xiě)操作都在內(nèi)存中,只有在close后才會(huì)保存到文件
r = open('江雪.txt','r',encoding='utf-8')
r.fileno()#返回文件描述符。中文返回3
r.flush()#操作完即保存到文件中,
r.close()
r.read()#單位為字符,可指定數(shù)量,默認(rèn)全部讀取
r.readline()#默認(rèn)一行
r.readlines()#默認(rèn)剩余所有內(nèi)容,顯示為一個(gè)列表
r.seek()#將光標(biāo)移動(dòng)到指定位置
r.tell()#查看當(dāng)前光標(biāo)的位置
r.truncate()#截?cái)?#xff0c;
r.write()
r ,只讀模式【默認(rèn)】
w,只寫(xiě)模式【不可讀;不存在則創(chuàng)建;存在則清空內(nèi)容;】
x, 只寫(xiě)模式【不可讀;不存在則創(chuàng)建,存在則報(bào)錯(cuò)】
a, 追加模式【可讀; 不存在則創(chuàng)建;存在則只追加內(nèi)容;】
"+" 表示可以同時(shí)讀寫(xiě)某個(gè)文件
r+, 讀寫(xiě)【可讀,可寫(xiě)】 w+,寫(xiě)讀【可讀,可寫(xiě)】 x+ ,寫(xiě)讀【可讀,可寫(xiě)】 a+, 寫(xiě)讀【可讀,可寫(xiě)】 "b"表示以字節(jié)的方式操作
rb 或 r+b wb 或 w+b xb 或 w+b ab 或 a+b
注:以b方式打開(kāi)時(shí),讀取到的內(nèi)容是字節(jié)類(lèi)型,寫(xiě)入時(shí)也需要提供字節(jié)類(lèi)型
r+:讀管自己讀,寫(xiě)的話,從最后開(kāi)始寫(xiě)
w+:首先就是清空,write之后進(jìn)行read,但是read是從write的光標(biāo)位置開(kāi)始讀
a+:光標(biāo)開(kāi)始就是最后,和r+的區(qū)別只是初始光標(biāo)位置
無(wú)法直接修改原文件,只能通過(guò)創(chuàng)建新文件,進(jìn)行修改和添加
with open('江雪.txt','r',encoding='utf-8') as r:#功能同上,只是退出with時(shí),自動(dòng)close
在Python 2.7 后,with又支持同時(shí)對(duì)多個(gè)文件的上下文進(jìn)行管理,即:
withopen('log1') as obj1,open('log2') as obj2:
r = open('江雪.txt','r',encoding='utf-8')
# for i in r.readlines():錯(cuò)誤姿勢(shì),可以執(zhí)行,但會(huì)一次性把所有的東西取到內(nèi)存中
for i in r:#正確的姿勢(shì):for內(nèi)部將r這個(gè)文件對(duì)象做成一個(gè)迭代器,用一行去一行。
def read(self, size=-1): #known case of _io.FileIO.read
"""注意,不一定能全讀回來(lái)
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
關(guān)閉文件pass
def fileno(self, *args, **kwargs): #real signature unknown
文件描述符pass
def flush(self, *args, **kwargs): #real signature unknown
刷新文件內(nèi)部緩沖區(qū)pass
def isatty(self, *args, **kwargs): #real signature unknown
判斷文件是否是同意tty設(shè)備pass
def read(self, *args, **kwargs): #real signature unknown
讀取指定字節(jié)數(shù)據(jù)pass
def readable(self, *args, **kwargs): #real signature unknown
是否可讀pass
def readline(self, *args, **kwargs): #real signature unknown
僅讀取一行數(shù)據(jù)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
截?cái)鄶?shù)據(jù),僅保留指定之前數(shù)據(jù)pass
def writable(self, *args, **kwargs): #real signature unknown
是否可寫(xiě)pass
def write(self, *args, **kwargs): #real signature unknown
寫(xiě)內(nèi)容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__
關(guān)閉文件"""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__
刷新文件內(nèi)部緩沖區(qū)"""flush() -> None. Flush the internal I/O buffer."""
pass
def isatty(self): #real signature unknown; restored from __doc__
判斷文件是否是同意tty設(shè)備"""isatty() -> true or false. True if the file is connected to a tty device."""
returnFalsedef next(self): #real signature unknown; restored from __doc__
獲取下一行數(shù)據(jù),不存在,則報(bào)錯(cuò)"""x.next() -> the next value, or raise StopIteration"""
pass
def read(self, size=None): #real signature unknown; restored from __doc__
讀取指定字節(jié)數(shù)據(jù)"""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__
讀取到緩沖區(qū),不要用,將被遺棄"""readinto() -> Undocumented. Don't use this; it may go away."""
pass
def readline(self, size=None): #real signature unknown; restored from __doc__
僅讀取一行數(shù)據(jù)"""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__
讀取所有數(shù)據(jù),并根據(jù)換行保存值列表"""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__
獲取當(dāng)前指針位置"""tell() -> current file position, an integer (may be a long integer)."""
pass
def truncate(self, size=None): #real signature unknown; restored from __doc__
截?cái)鄶?shù)據(jù),僅保留指定之前數(shù)據(jù)"""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__
寫(xiě)內(nèi)容"""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__
將一個(gè)字符串列表寫(xiě)入文件"""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內(nèi)置的open()函數(shù),打開(kāi)一個(gè)文件對(duì)象,在磁盤(pán)中讀寫(xiě)str、bytes
StringIO顧名思義就是在內(nèi)存中讀寫(xiě)str
BytesIO實(shí)現(xiàn)了在內(nèi)存中讀寫(xiě)bytes
我們把變量從內(nèi)存中變成可存儲(chǔ)或傳輸?shù)倪^(guò)程稱之為序列化
序列化之后,就可以把序列化后的內(nèi)容寫(xiě)入磁盤(pán),或者通過(guò)網(wǎng)絡(luò)傳輸?shù)絼e的機(jī)器上。
參考:https://www.cnblogs.com/yuanchenqi/articles/5782764.html
循環(huán)
if 條件1:
自拍
elif 條件2:
蹦
else:
跳舞
continue 結(jié)束本次循環(huán),繼續(xù)下一次循環(huán)
break 跳出整個(gè)當(dāng)前的循環(huán)(只能跳出一層)
If elif else 只執(zhí)行其中一個(gè)
但while else;for else執(zhí)行循環(huán)后,才執(zhí)行else
for循環(huán)
while循環(huán)
總結(jié)
以上是生活随笔為你收集整理的python 循环写文件_python-文件操作及循环的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 编程方法学13:字符串处理
- 下一篇: 编程方法学14:内存