python读写删除复制文件操作方法详细实例总结
作者:WDC 时间:2022-07-29 05:58:56
python读文件操作
1. read三种不同的方式
f = open('hello.txt') #'hello.txt'指的是文件的名称
while True:
text = f.readline() #读取文件指针指向的哪一行内容,然后指针下移
if text:
print(text)
else: #当文读到最后一行,三个空字符串
print(len(text))
break
f.close() #关闭文件,运行一下
f = open("hello.txt")
line_list = f.readlines() #一次性读取,以列表的形式表现出来
print(type(line_list))
for line in line_list:
print(line)
f.close()
f = open("hello.txt")
s = f.read() #一次性读取所有内蓉,并以字符串的形式返回
print(type(s))
for line in s:
print(line,end=' ')
f.close()
python写文件操作
2. writer的两种常用的基本方式
f = open('poet.txt','w',encoding='utf-8') #以写模式打开文件
f.write('你好,python') #写入内容
print("写入完毕,运行!")
f.close()
f = open("poet.txt",'a+')
print(f.read())
fruits = ['appple\n','banana\n','orange\n','watermelon\n']
f.writelines(fruits)
print('写入成功')
f.close()
python删除文件操作
3. delete删除
import os,os.path
if os.path.exists("sd.txt"):
os.remove("sd.txt")
print("删除成功")
else:
print('文件不存在')
删除相同文件的相同文件格式
import os
files = os.listdir('.') #列出指定目录下的所有文件和子目录
for filename in files:
point_index = filename.find(".") #获取'.‘在文件中出现的索引位置
if filename[point_index + 1:] == "txt": #判断当前文件的扩展名是否为'txt‘
os.remove(filename) #删除文件
python复制文件操作
4. copy复制
第1种方法
srcFile = open("a.txt") #源文件
destFile = open("a_copy.txt",'w') #目标文件
destFile.write(srcFile.read()) #将源文件中读取的内容写入目标文件
destFile.close()
srcFile.close()
print('复制完成')
第2种使用模块
with open("a.txt") as src,open("a_copy.txt",'w') as dest:
dest.write(src.read())
print('复制成功啦!')
更差关于python读写删除复制文件操作方法详细实例请查看下面的相关链接
标签:python,文件操作
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python3 打开外部程序及关闭的示例
2022-06-16 22:23:15
Python+OpenCV实现阈值分割的方法详解
2023-08-13 02:24:00
![](https://img.aspxhome.com/file/2023/0/77910_0s.jpg)
解决使用openpyxl时遇到的坑
2022-09-03 09:25:37
![](https://img.aspxhome.com/file/2023/3/107143_0s.jpg)
Vue Router根据后台数据加载不同的组件实现
2023-07-02 16:59:14
Python Selenium异常处理的实例分析
2021-01-12 17:13:06
Git撤销已经推送(push)至远端仓库的提交(commit)信息操作
2022-05-31 04:33:28
python3 下载网络图片代码实例
2021-11-21 01:11:40
Python 避免字典和元组的多重嵌套问题
2021-01-06 00:07:26
使用pycharm在本地开发并实时同步到服务器
2022-09-18 16:25:12
![](https://img.aspxhome.com/file/2023/2/103252_0s.png)
用ASP+CSS实现随机背景
2007-09-26 12:33:00
Python设计实现的计算器功能完整实例
2021-07-17 12:26:05
![](https://img.aspxhome.com/file/2023/4/127754_0s.png)
GoFrame通用类型变量gvar与interface基本使用对比
2024-04-27 15:26:26
![](https://img.aspxhome.com/file/2023/5/134215_0s.jpg)
html网页颜色表大全(苏昱)
2008-01-01 15:52:00
![](https://img.aspxhome.com/file/UploadPic/20081/1/200811162311168s.gif)
使用Python设置tmpfs来加速项目的教程
2023-12-24 09:38:34
优化MySQL的数据库性能的八种方法
2012-01-05 19:28:53
解决Pycharm 导入其他文件夹源码的2种方法
2023-03-02 08:32:54
浅谈python爬虫使用Selenium模拟浏览器行为
2021-04-23 22:26:46
![](https://img.aspxhome.com/file/2023/8/127148_0s.png)
Python Django 封装分页成通用的模块详解
2023-06-24 13:56:15
![](https://img.aspxhome.com/file/2023/3/103523_0s.png)
pandas的resample重采样的使用
2023-04-07 10:33:29
Python中请不要再用re.compile了
2021-08-30 23:57:51
![](https://img.aspxhome.com/file/2023/7/121657_0s.jpg)