VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
  • python基础教程之python基础教程之python文件操作-读写删除复制总结

本站最新发布   Python从入门到精通|Python基础教程
试听地址  
https://www.xin3721.com/eschool/pythonxin3721/


1. read三种不同的方式

1
2
3
4
5
6
7
8
9
= open('hello.txt')  #'hello.txt'指的是文件的名称
while True:
    text = f.readline()    #读取文件指针指向的哪一行内容,然后指针下移
    if text:
        print(text)
    else:  #当文读到最后一行,三个空字符串
        print(len(text))
        break
f.close()  #关闭文件,运行一下

 

 

1
2
3
4
5
6
= open("hello.txt")
line_list = f.readlines()  #一次性读取,以列表的形式表现出来
print(type(line_list))
for line in line_list:
    print(line)
f.close()

 

1
2
3
4
5
6
= open("hello.txt")
= f.read() #一次性读取所有内蓉,并以字符串的形式返回
print(type(s))
for line in s:
    print(line,end=' ')
f.close()

 

2. writer的两种常用的基本方式

1
2
3
4
= open('poet.txt','w',encoding='utf-8')  #以写模式打开文件
f.write('你好,python')  #写入内容
print("写入完毕,运行!")
f.close()

 

1
2
3
4
5
6
= open("poet.txt",'a+')
print(f.read())
fruits = ['appple\n','banana\n','orange\n','watermelon\n']
f.writelines(fruits)
print('写入成功')
f.close()

 

3. delete删除

1
2
3
4
5
6
import os,os.path
if os.path.exists("sd.txt"):
    os.remove("sd.txt")   
    print("删除成功")
else:
    print('文件不存在')

 

删除相同文件的相同文件格式

1
2
3
4
5
6
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种方法

1
2
3
4
5
6
srcFile = open("a.txt")  #源文件
destFile = open("a_copy.txt",'w')  #目标文件
destFile.write(srcFile.read()) #将源文件中读取的内容写入目标文件
destFile.close()
srcFile.close()
print('复制完成')

 

第2种使用模块

1
2
3
with open("a.txt") as src,open("a_copy.txt",'w') as dest:
    dest.write(src.read())
print('复制成功啦!')

 

【开发环境推荐】Cloud Studio是基于浏览器的集成式开发环境,支持绝大部分编程语言,包括 HTML5、PHP、Python、Java、Ruby、C/C++、.NET 小程序等等,无需下载安装程序,一键切换开发环境。 Cloud Studio提供了完整的 Linux 环境,并且支持自定义域名指向,动态计算资源调整,可以完成各种应用的开发编译与部署。
相关教程