首页 > 编程语言 > 详细

Python遍历文件夹和读写文件的方法

时间:2015-06-28 12:34:23      阅读:381      评论:0      收藏:0      [点我收藏+]

  

1、读取指定目录的文件
2、读取本地文件,输出文件内容
3、写入并保存一个文件到指定目录

  Python的代码非常简洁高效,实现以上三大功能仅用了40行左右的代码~ 之前用Java读写、创建、复制、重命名文件要写50多行代码,Python的效率的确很高;

#-*- 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)
    

 

Python遍历文件夹和读写文件的方法

原文:http://www.cnblogs.com/jackchiang/p/4605327.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!