结果如下: 文件夹D:\tomcat7\bin的信息: 文件夹的个数: 0 文件的个数: 28 Process finished with exit code 0
7,递归打印文件夹的方法:
1 2 3 4 5
defshowAllDirs(dp): tt=os.walk(dp); for l in tt: for lf in l[1]: print("目录的路径是:",l[0]+"\\"+lf)
递归打印文件的方法:
1 2 3 4 5
defshowAllDirsFiles(dirPath): tt=os.walk(dirPath); for l in tt: for ll in l[2]: print("文件的路径是:",l[0]+"\\"+ll)
8,读取文件的方法:
1 2 3 4 5 6
defreadFile(): f=open(r"D:///bbb.txt",encoding="UTF-8") for line in f: #去除多余的换行符 print(line.strip()) f.close();
批量载入读取:
1 2 3 4 5 6 7 8 9 10 11
defreadFile1(): f=open(r"D:///bbb.txt",encoding="UTF-8") while1: #print("j") lines=f.readlines(10000); ifnot lines: #print("end") break; for line in lines: print(line.strip()) f.close()
写入文件例子:
1 2 3 4 5 6 7 8 9 10 11 12 13
defwriteFile(): 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("写入成功!")