1 #coding:utf8
2 import os
3 import sys
4 def listfiles(rootDir, txtfile, label=0):
5 ftxtfile = open(txtfile, 'w')
6 list_dirs = os.walk(rootDir)
7 count = 0
8 dircount = 0
9 for root,dirs,files in list_dirs:
10 for d in dirs:
11 print(os.path.join(root, d))
12 dircount += 1
13 for f in files:
14 print(os.path.join(root, f))
15 ftxtfile.write(os.path.join(root, f)+ ' ' + str(label) + '\n')
16 count += 1
17 print(rootDir + ' has ' + str(count) + ' files')
18
19 listfiles('E:/data/pic', 'E:/data/txtfile.txt')

python 文件操作之open,read,write

1、open

#open(filepath , 'mode')

file = open(‘E:/data/testfile.txt’,‘w’)

一般常用模式:r(只读)、w(只写)、a(追加)、b(二进制)

组合:r+(读写)、w+(读写)

2、读文件(r): read()         readline()           readlines()

file = open('D/test/test.txt','r')   #只读模式打开file

3、write(w)

1 file = open('E:/data/txtfile.txt','w+')   #只写模式打开file
2 file.write('11111')

python的os.walk()函数的使用及对于root,dirs,files的理解

root指的是当前所在的文件夹路径,dirs是当前文件夹路径下的文件夹列表,files是当前文件夹路径下的文件列表。

所以我们可以通过root和dirs的某项组合出文件夹路径,通过root和files的某项组合出文件路径。

1 import os
2 path = r'E:\data\pic'
3 for root, dirs, files in os.walk(path):
4 #print(root, dirs, files)
5 for name in files:
6 print(os.path.join(root,name))
7 for name in dirs:
8 print(os.path.join(root,name))

最新文章

  1. Binary Tree Zigzag Level Order Traversal [LeetCode]
  2. 查看SQLServer最耗资源时间的SQL语句
  3. 转: __asm__ __volatile__内嵌汇编用法简述
  4. jq 的连续动画
  5. 看来ms sql server if 中定义个变量出了if 还是可以用的
  6. openURL的使用方法
  7. 各种计算机语言的经典书籍(C/C++/Java/C#/VC/VB等)
  8. MapReduce TotalOrderPartitioner 全局排序
  9. Windows安全事件日志中的事件编号与描述
  10. PureLayout
  11. shell中break 与 continue
  12. mysql安装报错
  13. eclipse:An internal error occurred during: "Build Project". GC overhead limit exceeded
  14. tensorflow第一篇---numpy模块
  15. C#+EntityFramework编程方式详细之Code First 数据迁移
  16. python爬取12306及各参数的使用。完整代码
  17. 重启电脑后,redis 6380端口关闭重启
  18. Code Chef IMPO(计算几何+扫描线+积分)
  19. OO 第三次博客总结
  20. elasticsearch搜索集群基础架构

热门文章

  1. Android使用volley发送带参数的post请求
  2. shell之flock
  3. python_test_0001_base_string_swap
  4. golang 实现twitter雪花算法
  5. [转]cfs 调度
  6. js var
  7. EBS的配置文件
  8. js常用代码整理2
  9. 阿里云ECS部署单机kafka 并对外提供服务(带认证)
  10. c基础-Makefile