美文网首页
文件操作

文件操作

作者: 四月四七日薄暮 | 来源:发表于2018-08-13 17:05 被阅读0次

    1、文件的打开与关闭

    (1) 打开文件

     f = open('test.txt','w')
    
    

    (2) 关闭文件

    #新建一个文件,文件名为:test.txt
    f = open('test.txt','w')
    #关闭这个文件
    f.close()
    
    

    (3)写入文件

    f = open('test.txt','w')
    f.write('hello world')
    
    

    (4)读文件

    f = open('test.txt', 'r')
    
    content = f.read(5)
    
    print(content)
    
    

    最重要的就是这四种方法 (1)打开、(2)、关闭(3)、写入(4)读

    2、文件的定位读写

    (1)获取当前读写的位置

    # 打开一个已经存在的文件
    f = open("test.txt", "r")
    str = f.read(3)
    print "读取的数据是 : ", str
    
    # 查找当前位置
    position = f.tell()
    print "当前文件位置 : ", position
    
    str = f.read(3)
    print "读取的数据是 : ", str
    
    # 查找当前位置
    position = f.tell()
    print "当前文件位置 : ", position
    
    f.close()
    
    

    (2)定位到某个位置

    下面是定位的方法:

        * offset:偏移量
        * from:方向
            * 0:表示文件开头
            * 1:表示当前位置
            * 2:表示文件末尾
    
    
    # 打开一个已经存在的文件
    f = open("test.txt", "r")
    str = f.read(30)
    print "读取的数据是 : ", str
    
    # 查找当前位置
    position = f.tell()
    print "当前文件位置 : ", position
    
    # 重新设置位置
    f.seek(5,0)
    
    # 查找当前位置
    position = f.tell()
    print "当前文件位置 : ", position
    
    f.close()
    
    

    3、文件的重命名和删除

    (1)重命名

    • 先导入一个os模块,然后用 rename()可以完成对文件的重命名操作
    import os
    os.rename("毕业论文.txt", "毕业论文-最终版.txt")
    
    

    (2)删除

    • os模块中的remove()可以完成对文件的删除操作,remove(待删除的文件名)
    import os
    os.remove("毕业论文.txt")
    
    

    4、文件夹的相关操作

    (1)创建文件夹

    import os
    os.mkdir("张三")
    
    

    (2)获取当前目录

    import os
    os.getcwd()
    
    

    (3)改变默认目录

    import os
    os.chdir("../")
    
    
    • (4)获取目录列表
    import os
    os.listdir("./")
    
    

    (5)删除文件夹

    import os
    os.rmdir("张三")
    
    

    相关文章

      网友评论

          本文标题:文件操作

          本文链接:https://www.haomeiwen.com/subject/hkvubftx.html