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()

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 = ['appplen','bananan','orangen','watermelonn']  f.writelines(fruits)  print('写入成功')  f.close()

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)   #删除文件

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('复制成功啦!')

  • 初学者学习python2还是python3?
  • python获取本机IP、mac地址、计算机名
  • 详解python2 和 python3的区别
  • python基础之删除文件及删除目录的方法
  • 用python求第1000个质数的值
  • python常用函数年初大总结
  • Python3 - 时间处理与定时任务
  • Python开发的CMS系统,Silva CMS 3 发布
  • python基础之使用os.system来执行系统命令
  • 判断python字典中key是否存在的两种方法
  • 初学者学习python2还是python3?
  • python基础之删除文件及删除目录的方法
  • python获取本机IP、mac地址、计算机名
  • python获取系统时间(时间函数详解)
  • 详解python2 和 python3的区别
  • 用python求第1000个质数的值
  • Python3 - 时间处理与定时任务
  • 命令行看糗百
  • Python算法之---冒泡,选择,插入排序算法
  • python 中求和函数 sum详解
  • range方法在Python2和Python3中的不同
  • python3 数组(列表)初始化
  • 记一次crontab中date命令错用导致的问题
  • MySQL用LIKE特殊字符搜索
  • CentOS 7 下修改主机名
  • Python3正则表达式之:(?(id/name)y...
  • TIOBE编程语言排行榜2019年 Python稳居前三
  • 解压命令unzip常用方法汇总
  • 解析redis备份文件rdb的两种方法及对比
  • 百度视觉语义化平台2.0:交互升级和...
  • 5G时代的视觉语义化技术:软硬结合...
  • 百度AutoDL重磅升级至3.0:设计、迁...