2021-03-16 python学习笔记(文件操作)

这篇博客详细介绍了Python的文件操作,包括打开和关闭文件、写入、读取字符、读取行、对行进行标号以及使用os模块进行文件重命名。通过示例展示了不同方法的用法和效果。

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

文件操作

1、打开文件

打开不存在的文件:

f=open('text.txt')#打开一个不存在的文件夹
Traceback (most recent call last):

  File "<ipython-input-1-fae403acd124>", line 1, in <module>
    f=open('text.txt')#打开一个不存在的文件夹

FileNotFoundError: [Errno 2] No such file or directory: 'text.txt'


f=open('text.txt','w')#打开一个不存在的文件夹

第一种运行方式会报错,第二种不会报错,会新建一个文件,区别是第二种代码加了文件的mode(访问模式),w的意思是,打开一个文件只用于写入。如果文件已存在,则覆盖,如果文件不存在,则新建一个文件。而第一种方式没有输入mode,则默认访问方式为r,即以只读方式打开文件并且指针放在文件头部,固会报错。

2、关闭文件

f.close
Out[3]: <function TextIOWrapper.close()>

关闭文件这个结果在显示页面中看不到。

3、在文件中进行写入操作

f=open('text.txt','w')#打开一个不存在的文件夹
f.write('hello world')
f.close
Out[8]: <function TextIOWrapper.close()>

然后打开python中的文件,找到text这个txt文件,可以发现输入后的结果如下:
在这里插入图片描述
close是为了之后别的程序可以继续访问这个文件。

4、读取某几个字符

f=open('text.txt','r')#r表示只读模式
result= f.read(3)#读取3个字符
print(result)
hel

result= f.read(3)#读取3个字符
print(result)
lo 

result= f.read(3)#读取3个字符
print(result)
wor

result= f.read(3)#读取3个字符
print(result)
ld

第一次打开的时候读前n个字符(定位在文件头部),每次重复执行命令的时候则往后移动n格。

5、读取行(readline)

f=open('text.txt','r')#r表示只读模式
result= f.readline()#读取一行
print(result)
hello world

readlines读取结果和readline不太相同

f=open('text.txt','r')#r表示只读模式
result= f.readlines()#读取一行
print(result)
['hello world']

对hello world 复制成五行以后再readlines:

f=open('text.txt','r')#r表示只读模式
result= f.readlines()#读取一行
print(result)
['hello world\n', 'hello world\n', 'hello world\n', 'hello world\n', 'hello world']

形成有五个元素的列表,将文档读成列表。

6、对每行进行标号

i=1;
for temp in result:
        print('%d:%s'%(i,temp))
        i+=1
1:hello world

2:hello world

3:hello world

4:hello world

5:hello world

如果用的是readline,(此时对第一行加了–1,以便区分)则:

f=open('text.txt','r')#r表示只读模式
result= f.readline()#读取一行
print('1:%s'%result)
1:hello world--1


result= f.readline()#读取一行
print('1:%s'%result)
1:hello world

可以发现,readline每次只能读一行,不够高效。

7、可以用os进行重命名

import os
os.rename('text.txt','text1.txt')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值