python读取文件下的所有图像[python] view plain copy
- #-*- coding: UTF-8 -*-
- '''''
- 1、读取指定目录下的所有文件
- 2、读取指定文件,输出文件内容
- 3、创建一个文件并保存到指定目录
- '''
- import os
- # 遍历指定目录,显示目录下的所有文件名
- def eachFile(filepath):
- pathDir = os.listdir(filepath)
- for allDir in pathDir:
- child = os.path.join('%s%s' % (filepath, allDir))
- print child.decode('gbk') # .decode('gbk')是解决中文显示乱码问题
- # 读取文件内容并打印
- def readFile(filename):
- fopen = open(filename, 'r') # r 代表read
- for eachLine in fopen:
- print "读取到得内容如下:",eachLine
- fopen.close()
- # 输入多行文字,写入指定文件并保存到指定文件夹
- def writeFile(filename):
- fopen = open(filename, 'w')
- print "\r请任意输入多行文字"," ( 输入 .号回车保存)"
- while True:
- aLine = raw_input()
- if aLine != ".":
- fopen.write('%s%s' % (aLine, os.linesep))
- else:
- print "文件已保存!"
- break
- fopen.close()
- if __name__ == '__main__':
- filePath = "D:\\FileDemo\\Java\\myJava.txt"
- filePathI = "D:\\FileDemo\\Python\\pt.py"
- filePathC = "C:\\"
- eachFile(filePathC)
- readFile(filePath)
- writeFile(filePathI)
- # -*- coding: utf-8 -*-
- import os
- def file_name(file_dir):
- for root, dirs, files in os.walk(file_dir):
- print(root) #当前目录路径
- print(dirs) #当前路径下所有子目录
- print(files) #当前路径下所有非目录子文件
- # -*- coding: utf-8 -*-
- import os
- def file_name(file_dir):
- L=[]
- for root, dirs, files in os.walk(file_dir):
- for file in files:
- if os.path.splitext(file)[1] == '.jpeg':
- L.append(os.path.join(root, file))
- return L
- #其中os.path.splitext()函数将路径拆分为文件名+扩展名
- # -*- coding: utf-8 -*-
- import os
- def listdir(path, list_name): #传入存储的list
- for file in os.listdir(path):
- file_path = os.path.join(path, file)
- if os.path.isdir(file_path):
- listdir(file_path, list_name)
- else:
- list_name.append(file_path)