摘要:本文主要向大家介绍了Python语言之python文件操作-读写删除复制总结,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
本文主要向大家介绍了Python语言之python文件操作-读写删除复制总结,通过具体的内容向大家展示,希望对大家学习Python语言有所帮助。
1. read三种不同的方式
f = open('hello.txt') #'hello.txt'指的是文件的名称while True:text = f.readline() #读取文件指针指向的哪一行内容,然后指针下移if text:print(text)else: #当文读到最后一行,三个空字符串print(len(text))breakf.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()
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()
3. delete删除
import os,os.pathif os.path.exists("sd.txt"):os.remove("sd.txt")print("删除成功")else:print('文件不存在')
删除相同文件的相同文件格式
import osfiles = os.listdir('.') #列出指定目录下的所有文件和子目录for filename in files:point_index = filename.find(".") #获取’.‘在文件中出现的索引位置if filename[point_index + 1:] == "txt": #判断当前文件的扩展名是否为’txt‘os.remove(filename) #删除文件
4. copy复制
srcFile = open("a.txt") #源文件destFile = open("a_copy.txt",'w') #目标文件destFile.write(srcFile.read()) #将源文件中读取的内容写入目标文件destFile.close()srcFile.close()print('复制完成')
with open("a.txt") as src,open("a_copy.txt",'w') as dest:dest.write(src.read())print('复制成功啦!')
本文由职坐标整理并发布,希望对同学们学习Python有所帮助,更多内容请关注职坐标编程语言Python频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号