当前位置:网站首页>文件及目录操作(5)
文件及目录操作(5)
2022-07-28 14:33:00 【WHJ226】
目录
1. 创建,打开和写入文件
打开文件一般使用with语句。
打开文件后,要及时关闭。如果忘记关闭,可能会带来意想不到的问题。为了避免问题的发生,需要使用with语句而不是open()方法。
一般语法格式如下:
with open(filename, mode='r') as f:
f.write(string)| 参数值 | 说明 | 备注 |
| r | 以只读模式打开文件。 | 文件必须存在。 |
| rb | 以二进制格式打开文件,并且采用只读模式。如图片、声音等。 | |
| r+ | 打开文件后,可以读取文件内容和写入新的内容并覆盖原内容。 | |
| rb+ | 以二进制格式打开文件,并采用读写模式。 | |
| w | 以只读模式打开文件。 | 如果文件存在,则将其覆盖;否则,创建新文件。 |
| wb | 以二进制格式打开文件,并且采用只读模式。如图片、声音等。 | |
| w+ | 打开文件后,先清空原有内容,使其变为一个空的文件,对这个空文件有读写权限。 | |
| wb+ | 以二进制格式打开文件,并且采用读写模式。 |
例如:
string = '打开douban文件'
with open('douban.txt', mode='r+',encoding='utf-8') as f: #将打开douban文件写入douban.txt,encoding='utf-8'为指定编码方式
f.write(string) #写入文件
with open('douban.txt', mode='r',encoding='utf-8') as a:
print(a.read()) #读取文件运行结果如下:
打开douban文件 #此内容是写入douban.txt中的内容。2. 目录操作
在python中,指定文件路径时,需要对路径分隔符\进行转义,即将路径中的\替换为\\。例如:对于相对路径"demo\m.txt"需要使用"demo\\m.txt"代替。另外,也可以将路径分隔符\采用/代替。
例如:
string = '打开douban文件'
path = 'E:/PYTHON/CSDN/csdn/' #指定路径
with open(path + 'douban.txt', mode='r+',encoding='utf-8') as f: #将打开douban文件写入douban.txt,encoding='utf-8'为指定编码方式
f.write(string) #写入文件
with open(path + 'douban.txt', mode='r',encoding='utf-8') as a:
print(a.read()) #读取文件运行结果如下:
打开douban文件 #此内容是写入douban.txt中的内容。边栏推荐
- 3、基本常数和宏定义
- ERROR:bokeh.core.validation. check:E-1001 (BAD_COLUMN_NAME)
- CANoe使用教程
- 1、开源GPS项目HD-GR GNSS的著作者
- 19、通道分配任务定义
- 机器学习的3大“疑难杂症”,因果学习是突破口 | 重庆大学刘礼
- Pyinstaller packages py as an EXE file
- RY-D1/1电压继电器
- Encapsulate the unified return object messageresult
- [touch] count the number of engineering documents, code lines, and line comment coverage
猜你喜欢

Learn PHP reflection classes from ThinkPHP remote code execution

SRTT-110VDC-4H-C时间继电器

In 2022, the average salary of global programmers was released, and China ranked unexpectedly

最小堆提升每次排序的效率

Explain the difference set, intersection set and union set of complex type set in detail.Net

基于RSocket协议实现客户端与服务端通信

详解.NET的求复杂类型集合的差集、交集、并集

How many tips do you know about using mock technology to help improve test efficiency?

R introduction example details

2022年全球程序员平均薪资发布,中国排名很意外
随机推荐
Differences between two ways of QT creating folders
Tencent interview -- please design a thread pool to implement sequential execution
19、通道分配任务定义
使用Mock技术帮助提升测试效率的小tips,你知道几个?
电压继电器DY-28C
Qt刷新UI界面问题
Pycharm - output exception of program run and default comment of added function
Crmeb knowledge paid manual installation tutorial
7、实时数据备份和实时时钟相关定义
sql 开发篇一 之 表锁查询及解锁
Requses template
For loop
7/13 (pond sampling)
Table lock query and unlocking in SQL development part 1
【LeetCode】35、搜索插入位置
.net core 3.1版本配置跨域问题
软件测试的流程规范有哪些?具体要怎么做?
Five connection modes of QT signal and slot
22、电文处理任务实现
Write a standard character device driver with your hands