当前位置:网站首页>文件及目录操作(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中的内容。边栏推荐
- 腾讯面试之--请你设计一个实现线程池顺序执行
- HJS-DE1/2时间继电器
- Qt信号与槽的五种连接方式
- Opencv - closely combine multiple irregular small graphs into large graphs
- Deepfacelab model parameters collection
- Tencent interview -- please design a thread pool to implement sequential execution
- Opencv - cut out mask foreground area from grayscale image
- Leetcode - random set, longest multiclass subsequence
- In 2022, the average salary of global programmers was released, and China ranked unexpectedly
- Configure CX Oracle solution (cx_oracle.databaseerror) dpi-1047: cannot locate a 64 bit Oracle client library: "th
猜你喜欢
随机推荐
Qt信号与槽的五种连接方式
JDS-12时间继电器
机器学习的3大“疑难杂症”,因果学习是突破口 | 重庆大学刘礼
【LeetCode】35、搜索插入位置
Installing CONDA and configuring Jupiter
提速1200倍!MIT开发新一代药物研发AI,吊打老模型
Deepfacelab model parameters collection
How many tips do you know about using mock technology to help improve test efficiency?
I heard that many merchants of crmeb have added the function of planting grass?
Grpc protocol buffer
腾讯面试之--请你设计一个实现线程池顺序执行
9、相关数据累积任务定义
ERROR:bokeh.core.validation.check:E-1001 (BAD_COLUMN_NAME)
[leetcode] binary search given an N-element ordered (ascending) integer array num and a target value target, write a function to search the target in num. if the target value exists, return the subscr
VS使用技巧
字符数组和字符串的区别
What are the functions to be added in crmeb pro2.2?
MIT指出公开预训练模型不能乱用
Leetcode - sliding window extremum, search tree postorder traversal, statistical difference pairs, dividing equal subsets
使用Mock技术帮助提升测试效率的小tips,你知道几个?








