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

Day02 Python之文件操作(open、read、write、close)

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

Day02 Python之文件操作(open、read、write、close)

一、file对象的属性

1、file.name
返回文件的名称
2、file.mode
返回文件的访问模式
3、file.closed
查看文件是否关闭,是TRUE,否FALSE

二、访问模式

r: 只读模式(默认); 文件必须存在
w: 只写模式; 不存在则创建,存在则重写
a: 追加模式; 不存在则创建,存在则只追加内容
+:表示可以同时读写某个文件
r+: 可读写文件,文件不存在抛出异常
w+:先写再读

三、打开文件

1、创建文件,内容为

2、open(文件路径,访问模式)

file=open('lwj.txt')
print(file)#<_io.TextIOWrapper name='lwj.txt' mode='r' encoding='cp936'>
file=open('lwj.txt')
print(file.name)#lwj.txt
file=open('lwj.txt')
print(file.mode)#r读取模式
file=open('lwj.txt')
print(file.closed)#False,代表文件没有关闭
file=open('D:/Study/day18.文件操作/lwj.txt')#在文件上鼠标右键--- copy path -- 粘贴
print(file.read(5))#hello

3、with
with:代码执行完,系统会自动调用f.close()方法

with open('test.txt', 'w', encoding='utf-8') as file:  
file.write('祝大家圣诞快乐!hello')

四、读文件

1、read()

file=open('lwj.txt')
print(file.read())#hello python

2、read(num)

num表示从文件中读取的数据的长度,如果没有传num值,默认读取所有内容
file=open('D:/Study/day18.文件操作/lwj.txt')#在文件上鼠标右键--- copy path -- 粘贴
print(file.read(5))#hello,最多读取5个

3、readline
一次读取一行内容,方法执行完,会把文件指针移动到下一行,准备再次读取

with open('test.txt', encoding='utf-8') as f:
    while True:
        text = f.readline()
        if not text:
            break
        print(text)#祝大家圣诞快乐!hello

4、readlines
按照行的方式把文件内容一次性读取,返回是一个列表,每一行的数据就是一个元素

将test.txt文件中的内容改为三行

with open('test.txt', encoding='utf-8') as f:
    con = f.readlines()
    print(con)#['祝大家n', '圣诞快乐!n', 'hello']
    print(type(con))#
for i in con:
    print(i)

五、写文件

1、追加模式; 不存在则创建,存在则只追加内容

file=open('lwj2.txt','a')
file.write('welcome')


2、先写后读

file=open('lwj2.txt','w+')
file.write('open the door')
p=file.tell()
print('第一次光标的位置:',p)#第一次光标的位置: 13
print(file.read())#读取的是空白


file.seek(0,0)#让光标从内容的开头读取
p2=file.tell()
print("第二次光标的位置:",p2)#第二次光标的位置: 0
print(file.read())#open the door
六、关闭文件
file=open('lwj.txt')
file.close()
print(file.closed)#True
七、目录文件

import os
1、文件重命名:os.rename(旧名, 新名)

 os.rename('lwj2.txt', 'we.txt')

2、删除文件:os.remove

os.remove('D:/Study/day18.文件操作/we.txt')

3、创建文件夹:os.mkdir

os.mkdir('zs')

4、删除文件夹:os.rmdir

os.rmdir('zs')

5、获取当前目录:os.getcwd

print(os.getcwd())

6、获取目录列表 os.listdir

print(os.listdir())  # 获取当前目录的列表
print(os.listdir('../'))  # 获取上一级目录的列表
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/822298.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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