Home  >  Article  >  Backend Development  >  Summary of Python file manipulation methods (collection)

Summary of Python file manipulation methods (collection)

黄舟
黄舟Original
2017-08-10 14:17:411127browse

这篇文章主要介绍了Python 操作文件的基本方法总结的相关资料,这里说明了九种操作文件的方法,并附上实现方法,需要的朋友可以参考下

Python 操作文件

编程语言对文件系统的操作是一项必不可少的功能,各种编程语言基本上都有对文件系统的操作,最简洁的莫过于linux里面shell的操作了,其次,则是python,ruby等动态语言的操作,那么,今天散仙来看下,在python里面如何使用一些常用的操作文件功能。

主要包括:

1,创建一个文件
2,删除一个文件
3,创建一个目录
4,删除一个目录
5,拷贝,重命名,查看文件大小
6,列出某个目录下文件的数量
7,递归打印某个目录下的所有文件和目录
8,读写文件操作
9,剪切,或者拷贝整个目录或文件到另一个位置下

1,创建文件方法:


f=open("D://111.cc",mode="w",encoding="UTF-8") 
f.close()

2,删除一个文件


import os 
os.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 os 
import 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 文件的个数: 28 
 
Process 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("写入成功!")

最后需要注意一点,注意路径的写法需要使用\\两个符号加转义实现,如果只写一个,可能会导致问题!

9,拷贝,或剪切的例子


#拷贝整个目录到另一个路径下 
shutil.copytree("E:\\11111111111\\a","E:\\11111111111\\b"); 
#剪切整个目录到另一个路径下 
shutil.move("E:\\11111111111\\a","E:\\11111111111\\cc")

The above is the detailed content of Summary of Python file manipulation methods (collection). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn