open()方法Python的open()方法用于打开一个文件,返回文件对象。该函数需要在处理文件的过程中使用。如果文件无法打开,将抛出OSError。(使用open()方法必须保证文件对象关闭,即调用close()方法)open(file,mode='r',buffering=-1,encoding=None,errors=None,newline=None,closefd=True,opener=None)file:必填,文件路径(相对或绝对路径)。mode:可选,文件打开方式buffering:设置缓冲区编码:一般使用utf8errors:错误级别newline:区分换行符closefd:传入文件参数类型文件对象的常用函数close()方法close()方法用于关闭一个对于一个打开文件,关闭的文件不能读写,否则会触发ValueError错误。允许多次调用close()方法。语法:fileObject.close();file=open("hello.txt","wb")print(file.name)file.close()#输出:hello.txtread()方法read()方法用于从一个文件中读取指定的数字字节数,如果未给出或为负数,则为全部。首先自己创建一个hello.txt文档(自定义的),文档中的内容是helloworld。file=open("hello.txt","r")read1=file.read()print(read1)file.close()#输出:helloworldwrite()方法write()方法用于写入指定文件到文件字符串。将helloworld写入一个空的hello.txt文件。file=open("hello.txt","w")file.write("helloworld")file.close()writelines()方法writelines()方法用于将字符串序列写入文件。这个字符串序列可以由一个可迭代的对象产生,比如一个字符串列表。换行需要指定换行符n。file=open("hello.txt","w")con=["a\n","b\n","c\n"]file.writelines(con)file.close()#hello.txt在文件中写入abcflush()方法。flush()方法用于刷新缓冲区,即将缓冲区中的数据立即写入文件,同时清空缓冲区。它不需要被动地等待写入输出缓冲区。通常情况下,缓冲区会在文件关闭后自动刷新,但如果需要在关闭前刷新,可以使用flush()方法。file=open("hello.txt","wb")print("filename:",file.name)file.flush()file.close()#filename:hello.txtreadline()方法readline()方法使用从文件中读取整行,包括“n”字符。如果指定了非负参数,则返回指定大小的字节数,包括“n”个字符。#hello.txt的内容123456789file=open("hello.txt","r")content=file.readline()print(content)file.close()#输出hello.txt文件的第一行:123readlines()方法readlines()方法用于读取所有行(直到结束字符EOF)并返回一个列表,可以用Python的for...in...结构进行处理。如果遇到终止符EOF,则返回一个空字符串。file=open("hello.txt","r")content=file.readlines()print(content)file.close()#输出:['123\n','456\n','789']seek()方法seek()方法用于将文件读取指针移动到指定位置。fileObject.seek(offset[,whence])offset表示起始偏移量,即需要移动的字节数。whence:可选,默认值为0。给offset参数一个定义,表示从哪里开始偏移;0表示从文件开头算起,1表示从当前位置算起,2表示从文件末尾算起。假设hello.txt文件中的内容是abcdefghijk,那么我们使用seek()方法移动文件指针:file=open("hello.txt","r")file.seek(3)#文件指针移动到第三位,从第四位开始读取print(file.read())#output:defghijkfile.seek(5)print(file.read())#output:fghijkfile.close()tell()methodtell()方法返回文件的当前位置,也就是文件指针的当前位置。file=open("hello.txt","r")file.seek(4)#文件指针移动到第三个位置,从第四个位置开始读取print(file.tell())#4file.close()fileno()方法fileno()方法返回一个整型文件描述符(filedescriptorfd整型),可用于底层操作系统的I/O操作。file=open("hello.txt","w")con=file.fileno()print(con)file.close()#输出:如果文件连接到终端设备,3isatty()方法返回True,否则返回False。file=open("hello.txt","w")con=file.isatty()print(con)file.close()#Output:Falsetruncate()方法truncate()方法用于截断文件,如果specified如果选择参数size,表示将文件截断为size个字符。如果未指定大小,则从当前位置截断;截断后,删除size之后的所有字符。#hello.txt文本abcdefile=open("hello.txt","r")con=file.readline()print(con)#output:afile.truncate()#截断字符串的其余部分con=file.readline()打印(con)文件。关闭()
