栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python 读写文件

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python 读写文件

 文件源代码
def open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True): 
    
    ===========================================================
    Character Meaning(mode)
    --------- -------------------------------------------------
    '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)

【写】 1.1 文件创建,并写入数据(全文替换):
“”“
文件不存在时,先创建文件,再写入数据。
文件存在时,直接将文件的内容删除后,写入write的内容。
“”“

file='/Users/lyx/软件测试/python/test/testfile.txt'
with open(file,'w') as a:
    a.write('这是第1行数据!')

备注:
1)直接使用open方法打开文件,结束需要使用close关闭文件,否则会占用系统资源;

2)使用with open读写文件,文件执行完毕后,自动关闭,无需使用close操作;

1.2 文件追加内容
file='/Users/lyx/软件测试/python/test/testfile.txt'
with open(file,'w') as a:
    a.write('这是第1行数据!')


"""
a:在文件末尾追加内容。
"""
with open(file,'a') as a:
    a.write('n')
    a.write('这是第2行数据!')

【读】 2.1 使用read()读取文件内容,返回str格式的内容。
file='/Users/moon/Lyx/test/python/Tenancy/files.txt'
with open(file,'w') as f:
    f.write('第1行')
    f.write('n')
    f.write('第2行')

with open(file,'r') as f:
    c=f.read()
    print(c)
    print('----------------------------------------------')
    print(type(c))

第1行
第2行
----------------------------------------------

2.2  使用readlines()读取文件内容,返回str格式的内容。
file='/Users/moon/Lyx/test/python/Tenancy/files.txt'
with open(file,'w') as f:
    f.write('第1行')
    f.write('n')
    f.write('第2行')

with open(file,'r') as f:
    c=f.readlines()
    print(c)
    print('----------------------------------------------')
    print(type(c))

['第1行n', '第2行']
----------------------------------------------

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/272858.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号