0
点赞
收藏
分享

微信扫一扫

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

Xin_So 2022-04-19 阅读 58
python

在这里插入图片描述

一、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))#<class 'list'>
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('../'))  # 获取上一级目录的列表
举报

相关推荐

0 条评论