在Python中文件读写删除复制操作怎么实现
Admin 2022-07-12 群英技术资讯 498 次浏览
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()
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()
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) #删除文件
第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('复制成功啦!')
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:mmqy2019@163.com进行举报,并提供相关证据,查实之后,将立刻删除涉嫌侵权内容。
猜你喜欢
pytorch是一个python优先的深度学习框架,用于自然语言应用程序,为了让大家了解pytorch的使用,下面给大家分享使用pytorch实现多项式回归的方法,有这方面学习需要的朋友可以参考学习。
这篇文章主要为大家详细介绍了如何利用Python语言实现邮件自动下载以及附件解析功能,文中的示例代码讲解详细,感兴趣的小伙伴可以了解一下
这篇文章给大家分享的是有关Python中怎样实现ascii转中文的内容,小编觉得挺实用的,因此分享给大家做个参考,下文还有中文转ascii的方法,感兴趣的朋友就接着往下看吧。
loc和iloc都是pandas工具中定位某一行的函数,下面这篇文章主要给大家介绍了关于Python学习之.iloc与.loc的区别、联系和用法的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
这篇文章给大家分享的是有关Python数据爬取的内容。下文有具体实例和方法,小编觉得挺实用的,因此分享给大家做个参考,接下来一起跟随小编看看吧。
成为群英会员,开启智能安全云计算之旅
立即注册Copyright © QY Network Company Ltd. All Rights Reserved. 2003-2020 群英 版权所有
增值电信经营许可证 : B1.B2-20140078 粤ICP备09006778号 域名注册商资质 粤 D3.1-20240008