文件常用操作
1.open
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): # known special case of open
"""
Open file and return a stream. Raise OSError upon failure.
翻译:打开一个文件并返回一个流,失败时抛出OSError
file is either a text or byte string giving the name (and the path
if the file isn't in the current working directory) of the file to
be opened or an integer file descriptor of the file to be
wrapped. (If a file descriptor is given, it is closed when the
returned I/O object is closed, unless closefd is set to False.)
翻译:文件要么是文本要么是字节字符串给出的将被打开的文件名字(如果文件不在当前工作路径中则是路径)
或者是一个数字文件的文件描述符将被包装的(如过文件描述符被给出,当返回I/O对象关闭时关闭,除非closefd设置为False
mode is an optional string that specifies the mode in which the file
is opened. It defaults to 'r' which means open for reading in text
mode. Other common values are 'w' for writing (truncating the file if
it already exists), 'x' for creating and writing to a new file, and
'a' for appending (which on some Unix systems, means that all writes
append to the end of the file regardless of the current seek position).
In text mode, if encoding is not specified the encoding used is platform
dependent: locale.getpreferredencoding(False) is called to get the
current locale encoding. (For reading and writing raw bytes use binary
mode and leave encoding unspecified.) The available modes are:
翻译: mode是一个可选选项,指定了在打开文件中使用的模式,默认是'r',意思是在文本模式打开。其他常用的值'w'意思是写入(如果文件已经存在
则清空文件),'x',是创建和写入一个新文件,'a'是追加(在一些unix系统中,等于全部写入追加到文件最后,不论当前指针在哪)
在文本模式下,如果编码不是当前平台支持的编码,则会调用locale.getpreferredencoding(False)来获取当前的编码(因为读和些原始字节都是用的二进制模式,不指定编码)可用的模式有下面几种:
========= ===============================================================
Character Meaning
--------- ---------------------------------------------------------------
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newline mode (deprecated)
========= ===============================================================
The default mode is 'rt' (open for reading text). For binary random
access, the mode 'w+b' opens and truncates the file to 0 bytes, while
'r+b' opens the file without truncation. The 'x' mode implies 'w' and
raises an `FileExistsError` if the file already exists.
翻译:默认的模式是'rt'(打开阅读)。如果是二进制的,那么模式’w+b'打开,并清空文件,如果是'r+b'模式打开文件没有清空。
’x'模式提供了‘w'和,如果文件存在返回FileExistsError.
Python distinguishes between files opened in binary and text modes,
even when the underlying operating system doesn't. Files opened in
binary mode (appending 'b' to the mode argument) return contents as
bytes objects without any decoding. In text mode (the default, or when
't' is appended to the mode argument), the contents of the file are
returned as strings, the bytes having been first decoded using a
platform-dependent encoding or using the specified encoding if given.
翻译:python 区分文件时以二进制还是文本模式 即时底层操作系统没有,文件以二进制模式打开(追加'b'到模式参数里面)返回没有任何解码内容作为二进制对象。
'U' mode is deprecated and will raise an exception in future versions
of Python. It has no effect in Python 3. Use newline to control
universal newlines mode.
翻译:'u'模式在未来版本会增加抛出异常的,在当前版本里面没有影响
buffering is an optional integer used to set the buffering policy.
Pass 0 to switch buffering off (only allowed in binary mode), 1 to select
line buffering (only usable in text mode), and an integer > 1 to indicate
the size of a fixed-size chunk buffer. When no buffering argument is
given, the default buffering policy works as follows:
翻译:buffering 是一个可选数字用来设置buffering策略。
0是用来关闭buffering ,1是选择行使用buffering,当大于1标识可变buffer。当没有buffering参数给出,则默认buffering策略如下:
* Binary files are buffered in fixed-size chunks; the size of the buffer
is chosen using a heuristic trying to determine the underlying device's
"block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
On many systems, the buffer will typically be 4096 or 8192 bytes long.
翻译:二进制文件以可变buffering,在许多系统中,buffer类型是4096或者8192字节长度
* "Interactive" text files (files for which isatty() returns True)
use line buffering. Other text files use the policy described above
for binary files.
翻译:交互式文件(isatty返回True)y用行buffering,其他文件用上面描述的二进制文件
encoding is the name of the encoding used to decode or encode the
file. This should only be used in text mode. The default encoding is
platform dependent, but any encoding supported by Python can be
passed. See the codecs module for the list of supported encodings.
翻译:encoding是使用编码或者解码的文件,这应该在文本模式中,默认的编码是平台支持的,但是多数支持的编码都可以。
errors is an optional string that specifies how encoding errors are to
be handled---this argument should not be used in binary mode. Pass
'strict' to raise a ValueError exception if there is an encoding error
(the default of None has the same effect), or pass 'ignore' to ignore
errors. (Note that ignoring encoding errors can lead to data loss.)
See the documentation for codecs.register or run 'help(codecs.Codec)'
for a list of the permitted encoding error strings.
翻译:errors是一个可选项制定了编码错误是被处理---这个参数不用于二进制模式。
newline controls how universal newlines works (it only applies to text
mode). It can be None, '', '\n', '\r', and '\r\n'. It works as
follows:
翻译:newline 控制全局换行生效模式(只用于文本模式),可以是None,'',\n,\r,\r\n
* 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.
翻译:在输入时,如果newline 是None, 全局的newlines模式都可用,lines 在插入时可以用\n,\r或者\r\n
并且这些被翻译为\n前返回给调用者。如果它是空,全局newlines模式可用,但是line结尾返回未翻译的给调用者。
如果是其他合法值,则插入的line只用给定的字符串,行结束使用未翻译的给调用者。
* 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.
翻译:在输出时,如果newline是None,任何\n字符串都被翻译 ,如果newline是空或者\n,那么不会被翻译,如果是其他合法的值,那么任何\n都会被翻译
If closefd is False, the underlying file descriptor will be kept open
when the file is closed. This does not work when a file name is given
and must be True in that case.
A custom opener can be used by passing a callable as *opener*. The
underlying file descriptor for the file object is then obtained by
calling *opener* with (*file*, *flags*). *opener* must return an open
file descriptor (passing os.open as *opener* results in functionality
similar to passing None).
open() returns a file object whose type depends on the mode, and
through which the standard file operations such as reading and writing
are performed. When open() is used to open a file in a text mode ('w',
'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
a file in a binary mode, the returned class varies: in read binary
mode, it returns a BufferedReader; in write binary and append binary
modes, it returns a BufferedWriter, and in read/write mode, it returns
a BufferedRandom.
It is also possible to use a string or bytearray as a file for both
reading and writing. For strings StringIO can be used like a file
opened in a text mode, and for bytes a BytesIO can be used like a file
opened in a binary mode.
"""
pass
2.close
- 关闭文件
- 通常使用with open 使用完后会自动关闭文件

1 #!/usr/bin/python 2 f=open('test','r',encoding='utf-8') 3 f.close()
3.seek
- 设置文件当前位置
- 一般和tell连用

1 #!/usr/bin/python 2 f=open('test','r',encoding='utf-8') 3 f.seek(2) 4 print(f.tell()) 5 f.close()
4.tell
- 返回文件当前位置(类似指针)

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 f.seek(2) 4 print(f.tell()) 5 f.close()
5.flush
- 刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件
- 可以连着write用

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 f.seek(2) 4 f.write('test') 5 f.flush() 6 f.close()
6.truncate(size)
- 截取到指定位置size,如size=4,则保留4个字符

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 f.truncate(4) 4 f.close()
7.write
- 将字符串写入文件

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 f.seek(2) 4 # print(f.tell()) 5 f.write('test') 6 f.close()
8.writelines
- 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 f.writelines(['test\n','test1']) 4 f.flush() 5 f.close()
9.read(size)
- 从文件读取指定的字节数

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 4 print(f.read()) 5 f.seek(0) 6 print('read-1',f.read(2)) 7 f.close()
10.readline
- 读取整行

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 print(f.readline()) 4 f.close()
11.readlines(size)
- 读取所有行并返回列表,以行的形式给出,若size,小于一行的内容,则返回指针到一行的位置

1 #!/usr/bin/python 2 f=open('test','r+',encoding='utf-8') 3 f.seek(0) 4 print(f.tell()) 5 print(f.readlines(50)) 6 7 f.seek(2) 8 print(f.tell()) 9 print(f.readlines(50)) 10 f.close()
人生没有白走的路,每一步都算数。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 因为Apifox不支持离线,我果断选择了Apipost!
· 通过 API 将Deepseek响应流式内容输出到前端