python基础~文件的读写

文件的读取:

with open()语句加read()方法读取文本文件

第一个参数是文件的路径,必填

第二个参数是读写模式,默认为r,读取模式

with open()不需要写close()方法

with open()可以一次处理多个文件

filepath = 'D:/note1.txt'

with open(filepath, encoding='utf-8' ) as file1:  #encoding='utf-8' or encoding='gbk'

    print(file1.read()) #读取文件的全部内容,返回值是str型

read() 读取文件的全部内容,返回值是字符串

readline() 读取文件一行的内容,返回值是字符串

readlines() 读取文件全部内容,返回值是列表,每一行为一个元素,保留换行符

read().splitlines() 读取文件全部内容,返回值是列表,且没有\n

filepath = 'D:/note1.txt'

with open(filepath, encoding='utf-8' ) as file1:

    print(file1.readline()) #读取文件一行的内容,返回值是str型

filepath = 'D:/note1.txt'

with open(filepath, encoding='utf-8' ) as file1:

    print(file1.readlines())  #读取文件的全部内容,返回值是列表,每一行是一个元素

filepath = 'D:/note1.txt'

with open(filepath, encoding='utf-8' ) as file1:

    print(file1.read().splitlines())  #读取文件的全部内容,返回值是列表,每一行是一个元素,且没有\n


绝对路径和相对路径:

绝对路径指文件在硬盘上的实际位置

D:/note1.txt    windows操作系统

/home/note1.txt    linux操作系统

相对位置指文件相对于当前文件的位置

./note1.txt    在当前文件所在目录里的note1.txt文件

../note1.txt    当前文件的上级目录里的note1.txt文件


文件的写入:

with open()语句加write()方法写入文本文件

第一个参数是文件的路径,必填

第二个参数是读写模式,选择w,清空写入;或选择a,追加写入

filepath = './note1.txt'

str1 = '春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。'

with open(filepath,'w',encoding='utf-8') as file1:

    file1.write(str1)

w+,可以同时读写,如果文件不存在,则新建文件,写入时,清空之前的内容

r+,可以同时读写,如果文件不存在,则报错,写入时是覆盖写入。写入多少内容则覆盖多少内容

a+,可以同时读写,如果文件不存在,则新建文件,写入时是追加写入

with open('./note3.txt','w+',encoding='utf-8') as file3:  #w+,如果文件不存在,则新建文件

    file3.write('春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。')

with open('./note3.txt','w+',encoding='utf-8') as file3:  #w+,写入时,清空之前的内容

    file3.write('疏是枝条艳是花,\n春妆儿女竞奢华。\n闲庭曲槛无余雪,\n流水空山有落霞。')

with open('./note4.txt','r+',encoding='utf-8') as file4:  #r+,如果文件不存在,则报错

    file4.write('春眠不觉晓,\n处处闻啼鸟。\n夜来风雨声,\n花落知多少。')

with open('./note3.txt','r+',encoding='utf-8') as file3:  #r+,写入时是覆盖写入。写入多少内容则覆盖多少内容

    file3.write('春眠不觉晓,\n处处闻啼鸟。')

with open('./note4.txt','a+',encoding='utf-8') as file4:  #a+,如果文件不存在,则新建文件

    file4.write('独寻青莲宇,\n行过白沙滩。\n一径入松雪,\n数峰生暮寒。')

with open('./note4.txt','a+',encoding='utf-8') as file4:  #a+,写入时是追加写入

    file4.write('一闪一闪亮晶晶,\n满天都是小星星。')

光标偏移

with open('./note3.txt','a+',encoding='utf-8') as file3:

    file3.write('qq')

    file3.seek(0)  #光标回到文件首位。seek(n)光标偏移n位。gbk格式的汉字占两个字节,utf-8格式的汉字占三个字节

    print(file3.read())

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容