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


    需求:
    1、读取指定目录下的所有文件
    2、读取指定文件,输出文件内容
    3、创建一个文件并保存到指定目录

    
    
    #-*- 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 "
    请任意输入多行文字"," ( 输入 .号回车保存)"
        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)
    
    
  • 相关阅读:
    linux解压分卷压缩的zip文件
    centos关闭sudo的ldap认证
    IT词汇表
    IT博客汇
    os.waitpid()无法获取sys.exit()退出时的status code
    github下fork后如何同步源的新更新
    git 撤销commit
    g++编译问题:skipping incompatible /usr/lib//libboost_system.so when searching for -lboost_system
    g++动态库静态库混合链接
    thread
  • 原文地址:https://www.cnblogs.com/ludundun/p/14164368.html
Copyright © 2020-2023  润新知