Python3.4操作文件目录
来源:互联网 发布:jquery 方法与js种方法 编辑:程序博客网 时间:2024/06/07 18:02
Python3.4操作文件目录
编程语言对文件系统的操作是一项必不可少的功能,各种编程语言基本上都有对文件系统的操作,最简洁的莫过于linux里面shell的操作了,其次,则是python,ruby等动态语言的操作,那么,今天先来看下,在python里面如何使用一些常用的操作文件功能。
主要包括:
1,创建一个文件
2,删除一个文件
3,创建一个目录
4,删除一个目录
5,拷贝,重命名,查看文件大小
6,列出某个目录下文件的数量
7,递归打印某个目录下的所有文件和目录
8,读写文件操作
1,创建文件方法:
f=open("D://111.cc",mode="w",encoding="UTF-8")f.close()
2,删除一个文件
import osos.remove("D://222.ccc123")os.close()
3,创建一个目录或多个目录
os.mkdir("E://bb")os.makedirs("D:\\a\\b")
4,删除依旧用remove方法或多级删除
os.removedirs(path)os.remove()
5,拷贝,重命名,查看文件大小
import osimport shutil#第一个参数是源文件,第二个拷贝文件shutil.copyfile("D://111.CC","D://222.ccc")os.rename("D://222.ccc","D://222.ccc123")os.stat("D://abc.txt").st_size
6,查看某个目录下文件数量:
def countDirs(dp): tt=tuple(os.walk(dp)) print("文件夹"+dp+"的信息:") print("文件夹的个数: ",len(tt[0][1]),"文件的个数: ",len(tt[0][2]))d1="D:\\tomcat7\\bin"countDirs(d1)
结果如下:
文件夹D:\tomcat7\bin的信息:文件夹的个数: 0 文件的个数: 28Process finished with exit code 0
7,递归打印文件夹的方法:
def showAllDirs(dp): tt=os.walk(dp); for l in tt: for lf in l[1]: print("目录的路径是:",l[0]+"\\"+lf)
递归打印文件的方法:
def showAllDirsFiles(dirPath): tt=os.walk(dirPath); for l in tt: for ll in l[2]: print("文件的路径是:",l[0]+"\\"+ll)
8,读取文件的方法:
def readFile(): f=open(r"D:///bbb.txt",encoding="UTF-8") for line in f: #去除多余的换行符 print(line.strip()) f.close();
批量载入读取:
def readFile1(): f=open(r"D:///bbb.txt",encoding="UTF-8") while 1: #print("j") lines=f.readlines(10000); if not lines: #print("end") break; for line in lines: print(line.strip()) f.close()
写入文件例子:
def writeFile(): a=list(); a.append("a你好") a.append("b哈喽") a.append("c") #a追加模式w覆盖模式 f=open("D://pp.txt",mode='a',encoding="UTF-8") print("文件大小:",f) for c in a: f.write(c+"\n") f.close() print("写入成功!")
最后需要注意一点,注意路径的写法需要使用\\两个符号加转义实现,如果只写一个,可能会导致问题!
0 0
- Python3.4操作文件目录
- Python3.4文件目录操作
- Python3.4操作文件目录(Windows下)
- Python3.2 --- 文件/目录操作
- Python3 - 文件与目录操作
- python3.2实现简单文件/目录操作
- 文件/目录操作( Python3.2)
- 【Python3】操作文件,目录和路径
- python3的文件与目录操作
- Python3中目录操作
- python3 目录操作
- Python3学习(31)--文件和目录的操作
- python3 操作Excel文件
- python3的文件操作
- python3 文件操作
- python3操作csv文件
- file 文件操作 python3
- python3 操作文件相关
- 显示*** missing separator (did you mean TAB instead of 8 spaces?) 解决方案
- SQLite数据库
- HDU5095 Linearization of the kernel functions in SVM(模拟)
- javaScript简单实现ajax
- 理解hadoop的Map-Reduce数据流(data flow)
- Python3.4操作文件目录
- poj 1543 Perfect Cubes
- ubuntu14.04 安装 wordpress
- [LeetCode]Binary Tree Zigzag Level Order Traversal
- iOS c 语言中两个参数的含义
- [中级数据结构学习笔记]一、Treap
- linux (一)(基础命令及文件相关命令)
- 白话经典算法系列之六 快速排序 快速搞定
- Maven学习笔记——使用Archetype生成项目骨架