Python中对文件的相关操作

本文详细介绍了Python中对文件的操作,包括打开、读写、追加等模式,以及文件指针的使用。讲解了read、readline、readlines等方法,并通过实例演示了不同模式下对文件内容的影响。还提到了二进制文件的读取以及上下文管理器在确保文件关闭上的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.打开文件的三个步骤:打开---->写入----->关闭

打开文件就会在系统中占用文件描述符,不关闭的话会浪费系统中的文件描述符,他有一个最大限度

f = open('/mnt/test')
f.read()
f.close()

注:读取内容之后不会有显示,需要一个东西传递这可内容才会与有输出
f.read默认是只读方式打开,不可写
f.writable()是否可写
f.readable()是否可读

f = open('/mnt/test')
content = f.read()
print(content)
print(f.writable())
print(f.readable())
f.close()

结果:
hello
happy
hahah

False
True

2.文件的读写(文本文件)

(1)r:默认
只能读不能写
读取的文件不存在会报错

(2)r+:
可以执行读写操作
文件不存在会报错
默认情况下从文件指针所在位置开始写入

(3)w:
write only
会清空文件之前的内容
文件不存在不会报错,会创建新的文件并写入

(4)w+:
可读可写
会清空源文件内容
文件不存在时不会报错,会建立文件并写入

(5)a:
write only
不会清空文件内容,
文件不存在会建立文件

(6)a+:
可读可写
不会清空原来的内容,在末尾追加
文件不存在会自动建立并写入

实验:
1)r 可读不可写

f = open('/mnt/test','r')
# content = f.read()
# print(content)
print(f.writable())
print(f.readable())
f.close()

结果:
False
True

如果要写入的话会出现报错

f = open('/mnt/test','r')
# content = f.read()
# print(content)
print(f.writable())
print(f.readable())
f.write('你好')
f.close()

结果:
Traceback (most recent call last):
  File "/home/kiosk/PycharmProjects/westos/python06/test.py", line 14, in <module>
    f.write('你好')
io.UnsupportedOperation: not writable
False
True

2)r+ 可读可写
<1>给已经存在的文件中写入

f = open('/mnt/test','r+')
print(f.writable())
print(f.readable())
f.write('你好')
f.close()
结果:
True
True

查看文件中的内容,原来的一部分内容被覆盖

[kiosk@foundation68 mnt]$ cat test 
你好happy
hahah

<2>给不存在的文件中写入,会出现报错

f = open('/mnt/test1','r+')
print(f.writable())
print(f.readable())
f.write('你好')
f.close()
结果:
Traceback (most recent call last):
  File "/home/kiosk/PycharmProjects/westos/python06/test.py", line 9, in <module>
    f = open('/mnt/test1','r+')
FileNotFoundError: [Errno 2] No such file or directory: '/mnt/test1'

3)w
<1>给已经存在的文件中写入

f = open('/mnt/test','w')
print(f.writable())
print(f.readable())
f.write('你好1')
f.close()
结果:
True
False

查看文件内容,原来的内容被清空

[kiosk@foundation68 mnt]$ cat test 
你好1

<2>给不存在的文件中写入,出现报错没有权限

f = open('/mnt/test1','w')
print(f.writable())
print(f.readable())
f.write('hello w')
f.close()
结果:
Traceback (most recent call last):
  File "/home/kiosk/PycharmProjects/westos/python06/test.py", line 9, in <module>
    f = open('/mnt/test1','w')
PermissionError: [Errno 13] Permission denied: '/mnt/test1'

切换到超级用户给/mnt满权限

[kiosk@foundation68 mnt]$ su - root
Password: 
Last login: Sat Apr  6 04:10:22 CST 2019 on pts/0
[root@foundation68 ~]# chmod 777 /mnt

再次执行

f = open('/mnt/test1','w')
print(f.writable())
print(f.readable())
f.write('hello w')
f.close()
结果:
True
False

查看目录中出现新的文件,查看文件内容

[kiosk@foundation68 mnt]$ ls
pycharm-community-2018.3  pycharm-community-2018.3.tar.gz  test  test1
[kiosk@foundation68 mnt]$ cat test1
hello w

4)w+
<1>存在的文件

f = open('/mnt/test','w+')
print(f.writable())
print(f.readable())
f.write('hello w+')
f.close()
结果:
True
True

查看文件内容

[kiosk@foundation68 mnt]$ cat test
hello w+

<2>不存在的文件

f = open('/mnt/test2','w+')
print(f.writable())
print(f.readable())
f.write('hello w+ 不存在')
f.close()
结果:
True
True

查看文件内容

[kiosk@foundation68 mnt]$ ls
pycharm-community-2018.3  pycharm-community-2018.3.tar.gz  test  test1  test2
[kiosk@foundation68 mnt]$ cat test2
hello w+ 不存在

5)a
<1>文件存在时

f = open('/mnt/test','a')
print(f.writable())
print(f.readable())
f.write('hello a 存在')
f.close()
结果:
True
False

查看文件内容

  [kiosk@foundation68 mnt]$ cat test
  hello w+hello a 存在

<2>文件不存在时

f = open('/mnt/test3','a')
print(f.writable())
print(f.readable())
f.write('hello a 不存在')
f.close()
结果:
True
False

查看文件内容

[kiosk@foundation68 mnt]$ cat test3
hello a 不存在

6)a+
<1>文件存在时

f = open('/mnt/test','a+')
print(f.writable())
print(f.readable())
f.write('hello a+ 存在')
f.close()
结果:
True
True

查看文件内容

[kiosk@foundation68 mnt]$ cat test
hello w+hello a 存在hello a+ 存在

<2>文件不存在时

f = open('/mnt/test4','a+')
print(f.writable())
print(f.readable())
f.write('hello a+ 不存在')
f.close()
结果:
True
True

查看文件内容

[kiosk@foundation68 mnt]$ cat test4
hello a+ 不存在

总结:查看文件内容时会直接在文件内容后输出一个命令行,这是因为,读完文件之后文件指针在末尾处

3.文件指针

(1)readlines():读取文件内容,返回一个列表,列表的元素分别为文件
行内容
(2)默认情况下读取文件的所有内容,小文件可以直接用read读取,如果
是大文件(文件大小>内存大小),不能通过read一次性读取所有内容
(3)seek方法,移动指针
seek的第一个参数是偏移量:>0,表示向右移动,<0表示向左移动
seek的第二个参数是:
0:移动指针到文件开头
1:不移动指针
2:移动指针到末尾

1)查看当前指针所在的位置f.tell()

f = open('/mnt/test4','a+')
print(f.writable())
print(f.readable())
print(f.tell())

f.write('python')

print(f.tell())
content = f.read()
print(content)

f.close()
结果:
True
True
18
24

总结:可以看出对文件写时在上一次操作之后文件指针坐在的位置开始写的

2)区别read(),readilne()和readlines()

<1>read(),读取文件内容在一行输出

f = open('/mnt/test','rb')
print(f.read())
结果:
b'hello\nhappy\nhahah\ngege\nyunyun\n'

<2>readilne(),读取文件内容,写入几行readilne(),输出几行

f = open('/mnt/test','rb')
print(f.readline())
结果:
b'hello\n'

写入两行,readilne()

f = open('/mnt/test','rb')
print(f.readline())
print(f.readline())
结果:
b'hello\n'
b'happy\n'

<3>readilnes(),读取文件内容,返回一个列表,列表的元素分别是文件内行的内容

f = open('/mnt/test','rb')
print(f.readline())
print(f.readlines())
结果:
b'hello\n'
[b'happy\n', b'hahah\n', b'gege\n', b'yunyun\n']

3)取出文件的前四个字符(相当于head -c 4)

f = open('/mnt/test','rb')
print(f.read(4))
f.close()
结果:
b'hell'

4)关于文件指针的位置(难点)

f = open('/mnt/test','rb')
print(f.read(4))
print(f.readline())
f.close()
结果:
b'hell'
b'o\n'

总结:第一次操作时截取文件的前四个字符,这时文件指针就在l的位置上,下一次操作是读取第一行,这时只会从文件指针的位置开始读到出现换行符才结束,所以这一行输出的结果是o\n

f = open('/mnt/test','rb+')
print(f.tell())
print(f.read(3))
print(f.tell())
结果:
0
b'hel'
3

5)去掉文件每一行的空格(strip 取出广义的空格,\n \t 都属于广义的空格)

f = open('/mnt/test','rb')
print([line.strip() for line in f.readlines()])
f.close()
结果:
[b'hello', b'happy', b'hahah', b'gege', b'yunyun']

6)seek方法(重点,难点)

f = open('/mnt/test','rb+')
print(f.tell())
f.seek(-1,2)   #指针移动到末尾在向左移动一个位置
print(f.read())
print(f.tell())
f.seek(0,1)   ##指针不移动
print(f.tell())
f.seek(0)   ##移动到文件开头
print(f.tell())
f.close()

结果:
0
b'\n'
30
30
0

4.非纯文本文件读取

(1)读取二进制文件

rb rb+ wb wb+ ab ab+
没有报错就表示读取到

f1 = open('hello.png',mode='rb')
content = f1.read()
f1.close()
没有报错

(2)复制

f1 = open('hello.png',mode='rb')
content = f1.read()
f1.close()

f2 = open('111.jpg',mode='wb')
f2.write(content)
f2.close()

会生成一个文件111.jpg,打开这个文件的可以看到他的内容和hello.png完全相同

5.上下文管理器
有时候打开文件忘记关闭,可以用这种方法解决
不用写f.close()

#同时打开两个文件
with open('/mnt/test') as f1,\
    open('/mnt/test1','w+') as f2:
    #将第一个文件的内容写入第二个文件中
    f2.write(f1.read())
    #移动指针到文件最开始
    f2.seek(0)
    #读取文件内容
    print(f2.read())

结果:
hello
happy
hahah
gege
yunyun

练习:

创建文件data.txt,文件共100000行,每行存放一个1~100之间的整数

import random

f = open('data.txt','a+')
for i in range(100000):
    f.write(str(random.randint(1,100)) + '\n')
f.seek(0)
print(f.read())
f.close()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值