好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

关于Python操作文件方法的总结(收藏)

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

f=open("D://111.cc",mode="w",encoding="UTF-8") 
f.close() 
import os 
os.remove("D://222.ccc123") 
os.close() 
os.mkdir("E://bb") 
os.makedirs("D:\\a\\b") 
os.removedirs(path) 
os.remove() 
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 
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 
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) 
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("写入成功!") 
#拷贝整个目录到另一个路径下 
shutil.copytree("E:\\11111111111\\a","E:\\11111111111\\b"); 
#剪切整个目录到另一个路径下 
shutil.move("E:\\11111111111\\a","E:\\11111111111\\cc") 

以上就是关于Python操作文件方法的总结(收藏)的详细内容,更多请关注Gxl网其它相关文章!

查看更多关于关于Python操作文件方法的总结(收藏)的详细内容...

  阅读:45次