python入门-------文件打开、写入、读取、关闭操作

    技术2022-07-11  107

    文章目录

    文件的读写操作常用的文件打开模式'w''a''b' 文件对象的常用方法read()readline()readlines()write()writelines()seek()tell()flush() encoding='utf-8'with open('a.txt', 'r') as file:10.1 从文件中读取数据10.1.1 读取整个文件使用with打开文件结尾就不需要关闭文件 10.1.2 文件路径相对路径绝对路径 10.1.3 逐行读取10.1.4 创建一个包含文件各行内容的列表readlines() 10.1.5 使用文件的内容 10.2 写入文件10.2.1 写入空文件write() 10.2.2 写入多行: \n10.2.3 附加到文件:'a'

    文件的读写操作

    内置函数open()创建文件对象 语法规则:

    file = open(filename [,mode,encoding])

    file:被创建的文件对象 open:创建文件对象的函数 filename:要创建或打开的文件名称 mode:打开默哀是默认为只读 encoding:默认文本文件中字符的编写格式为gbk

    例:读取磁盘文件的内容

    file = open('a.txt', 'r') print(file.readlines()) file.close() ['中国\n', '美丽']

    常用的文件打开模式

    按文件中数据的组织形式,文件分为以下两大类 文本文件:存储的是普通“字符文本”,默认为unicode字符集,可以使用记本事程序打开 二进制文件:把数据内容用“字节”进行存储,无法用记事本打开,必须使用专用的软件打开,举例:mp3音频文件,jpg图片,doc文档等

    打开模式执行操作’r’以只读方式打开文件(默认)’w’以写入的方式打开文件,会覆盖已存在的文件‘x’如果文件已经存在,使用此模式打开将引发异常’a’以写入模式打开,如果文件存在,则在末尾追加写入’b’以二进制模式打开文件,不能单独使用,需要与其它模式一起使用,如rb,wb‘t’以文本模式打开(默认)’+'以读写模式打开,不能单独使用,需要与其它模式一起使用,如a+‘U’通用换行符支持

    ‘w’

    1、open以写入的方式打开一个不存在的文件,便能创建一个新文件

    file = open('b.txt', 'w') file.write('helloworld') file.close()

    2、再次以写入的形式写进创建好的文件,便覆盖文件的内容

    file = open('b.txt', 'w') file.write('python') file.close()

    例2: 这里有两种打开文件的方法,同时两种写入文件的方法

    # 一,使用print方式进行输出() fp = open('text.txt', 'w') print('奋斗成就更好的你', file=fp) # 这里也可以f.write() fp.close() """第二种方式,使用文件读写操作""" with open('text1.txt', 'w') as file: file.write('奋斗成就更好的你')

    ‘a’

    把上述代码的’w’改成’a’,再运行一次,便在原来的基础上追加,所以结果显示两个python

    file = open('b.txt', 'a') file.write('python') file.close()

    但如果原来没有这个文件,便创建,如以下代码在不存在的c文件中写入

    file = open('c.txt', 'a') file.write('python') file.close()

    ‘b’

    这里进行图片的赋值,原图片为win.png,复制后命名为copy.png

    # 进行图片的复制 src_file = open('win.png', 'rb') # 原文件,二进制读 target_file = open('copy.png', 'wb') # 目标文件,二进制写 target_file.write(src_file.read()) # 原文件读出,写入目标文件 target_file.close() # 关闭两个文件 src_file.close()

    结果如下:

    文件对象的常用方法

    文件对象方法执行操作read([size])从文件中读取size个字节或字符的内容返回。若省略[size],则读取到文件末尾,即一次读取文件所有内容readline()从文本文件中读取一行内容readlines()把文本文件中每一行都作为独立的字符串对象,并将这些对象放入列表返回write(str)将字符串str内容写入文件wirtelines(s_list)将字符串列表s_list写入文本文件,不添加换行符seek(offset[,whence])把文件指针移动到新的位置,offset表示相对于whence的位置;offset为正往结束方向移动,为负往开始方向移动。whence不同的值代表不同含义:0:从文件头开始计算(默认值);1:从当前位置开始计算;2:从文件尾开始计算tell()返回文件指针的当前位置truncate([size=file.tell()])截取文件到size个字节,默认是截取到文件指针当前位置flush()把缓冲区的内容写入文件,但不关闭文件close()关闭文件

    read()

    file = open('a.txt', 'r') print(file.read())

    readline()

    读一行

    file = open('a.txt', 'r') #print(file.read()) print(file.readline())

    readlines()

    将每一行元素作为独立字符串,放入列表当中

    file = open('a.txt', 'r') #print(file.read()) #print(file.readline()) print(file.readlines()) ['中国\n', '美丽']

    write()

    file = open('c.txt', 'w') file.write('hello') file.close()

    writelines()

    将字符串列表s_list写入文本文件,不添加换行符

    file = open('c.txt', 'a') lst = ['java', 'go', 'python'] file.writelines(lst) file.close()

    seek()

    file = open('a.txt', 'r') file.seek(2) # 一个中文两个字节,跳过了国字 print(file.read()) print(file.tell()) # 中国,回车,美丽总共10字节 file.close() 国 美丽 10

    tell()

    file = open('b.txt', 'r') print(file.read()) print(file.tell()) # 中国,回车,美丽总共10字节 file.close() pythonpython 12

    flush()

    file = open('d.txt', 'a') file.write('hello') file.flush() # 后面可以继续写内容 file.write('world') file.close() # 后面不可以写代码

    encoding=‘utf-8’

    f = open('C:\\Users\\zdb\\Desktop\\abc.txt', encoding='utf-8') #encoding='utf-8' 防止乱码加上去的 print(f) print(f.read()) #对的,读,并输出 <_io.TextIOWrapper name='C:\\Users\\zdb\\Desktop\\abc.txt' mode='r' encoding='utf-8'> abcdefg

    例2

    file_name = input('请输入需要打开的文件名:') f = open(file_name) print('文件的内容是:') for each_line in f: print(each_line)

    with open(‘a.txt’, ‘r’) as file:

    这样就不需要关闭文件那一行代码了

    with open('a.txt', 'r') as file: print(file.read()) 中国 美丽

    例2

    with open('win.png', 'rb') as file: # 以二进制读打开 with open('copy.png', 'wb') as target_file: # 以二进制写打开 target_file.write(file.read()) # 目标文件写入原文件被读的

    读取文本时,python将其中的所有文本都解读为字符串

    10.1 从文件中读取数据

    要使用文本文件中的信息,首先需要将信息读取到内存中。为此,你可以一次性读取文件的全部内容,也可以每次一行的方式逐步读取。

    10.1.1 读取整个文件

    1、先创建一个txt文件文件,写入一点东西,与程序放在同一目录下 2、写入以下代码

    使用with打开文件结尾就不需要关闭文件

    with open('pi_digits.txt') as file_object: #open接受一个参数:要打开的文件的名称 #关键字with在不需要访问文件后将其关闭 contents = file_object.read() #read读取这个文件的全部内容,并将其作为长串字符存储在变量contents中 print(contents) #打印输出

    3、输出

    3.1414826 123456 654321

    4、为什么有一个空行呢? 在read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。删除空行,可在print语句中使用rstrip()函数。 删除前 删除后

    10.1.2 文件路径

    相对路径

    只能读取到同一目录里面的文件 1、text_files与主程序在一个目录 2、读取text_file里面的pi_digits.txt 3、主程序代码如下

    with open('text_files\pi_digits.txt') as file_object: #open接受一个参数:要打开的文件的名称 #关键字with在不需要访问文件后将其关闭 contents = file_object.read() #read读取这个文件的全部内容,并将其作为长串字符存储在变量contents中 print(contents) #打印输出

    4、输出结果与上节相同

    绝对路径

    读取系统任何地方的文件

    f = open('C:\\Users\\zdb\\Desktop\\abc.txt', encoding='utf-8') #encoding='utf-8' 防止乱码加上去的 print(f) print(f.read()) #对的,全输出

    10.1.3 逐行读取

    读取文件时,常常需要检查其中的每一行:你可能要在文件中查找特定的信息,或者要以某种方式修改文件中的文本。 要以每次一行的方式检查文本,可对文件对象使用for循环:

    filename = 'pi_digits.txt' with open(filename) as file_object: for line in file_object: print(line) 3.1414826 123456 654321

    为何会出现这些空白行呢? 是因为在这个文件中,每行的末尾都有一个看不见的换行符,而print语句也会加上一个换行符,因此每行末尾都有两个换行符:一个来自文件,另一个来自print语句。要消除,使用rstrip()。 1、代码 2、输出结果 例2

    f = open('C:\\Users\\zdb\\Desktop\\abc.txt', encoding='utf-8') #f.seek(0,0) lines = list(f) for each_line in lines: print(each_line) abcdefg 123 456

    10.1.4 创建一个包含文件各行内容的列表

    readlines()

    使用关键字with时,open()返回的文件对象只在with代码块内可用。 如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表。

    filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip()) 3.1414826 123456 654321

    10.1.5 使用文件的内容

    filename = 'pi_digits.txt' with open(filename) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() print(pi_string) print(len(pi_string)) 3.1414826123456654321 21

    10.2 写入文件

    保存数据的最简单的方式之一是将其写入文件中。通过将输出写入文件,即便关闭包含程序输出的终端窗口,这些输出也依然存在。

    10.2.1 写入空文件

    write()

    注意:python只能将字符串写入 读取模式(‘r’) 写入模式(‘w’) 附加模式(‘a’) 读取和写入模式(’'r+) 如果省略了,默认为只读模式(‘r’)

    filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.")

    1、如果写入的文件不存在,函数open()将自动创建它。 2、如果已经存在,python将在返回文件对象前清空文件。 例2

    f = open('E:\\text.txt','w') print(f.write('huzz猪')) 5

    10.2.2 写入多行: \n

    函数write()不会在你写入的文本末尾添加换行符,因此如果你写入多行时没有指定换行符,文件看起来可能不是你希望的那样

    filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.") file_object.write("I love creating new games.")

    例2

    filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming.\n") file_object.write("I love creating new games.")

    10.2.3 附加到文件:‘a’

    如果你需要给文件添加内容,而不是覆盖原有的内容,可以附加模式打开文件。 附加模式打开文件,不会清空文件原有的内容。

    filename = 'programming.txt' with open(filename, 'a') as file_object: # file_object.write("I love programming.\n") # file_object.write("I love creating new games.") file_object.write("\n\nI also love finding meaning in large datasets.\n") file_object.write("I love creating apps that can run in a browser.")

    Processed: 0.014, SQL: 9