• python操作文件和目录


    python操作文件和目录

    目录操作

    # 查看当前目录
    >>> os.path.abspath('.')
    '/Users/markzhang/Documents/python/security'
    # 查看当前目录
    >>> os.getcwd()
    '/Users/markzhang/Documents/python/security'
    # 更改当前的工作目录
    >>> os.chdir('/Users/markzhang/')
    >>> os.getcwd()
    '/Users/markzhang'
    # 在某目录下创建新目录,首先显示新目录的完整路径
    >>> os.path.join('/Users/markzhang/Documents/python/security','test')
    '/Users/markzhang/Documents/python/security/test'
    # 创建目录
    >>> os.mkdir('/Users/markzhang/Documents/python/security/test')
    # 删除目录
    >>> os.rmdir('/Users/markzhang/Documents/python/security/test')
    

    文件操作

    # 创建文件
    >>> with open('/Users/markzhang/Documents/python/security/demo.txt','w') as f:
    ...     f.write('hello world')      # 写文件
    ...
    >>> with open('/Users/markzhang/Documents/python/security/demo.txt','r') as f:
    ...     f.read()                    # 读文件
    ...
    'hello world'
    >>> os.getcwd()
    '/Users/markzhang/Documents/python/security'
    # 对文件重命名
    >>> os.rename('demo.txt','test.txt')
    # 删除文件
    >>> os.remove('test.txt')
    

    实例

    将0-9写入到指定文件,并以当前时间命名

    import os
    import time
    
    def current_time():
    	t = time.strftime('%Y-%m-%d',time.localtime())
    	suffix = ".txt"
    	fullname = t+suffix
    	return fullname
    
    with open('/Users/markzhang/Desktop/io.txt','w') as f:
    	for i in range(10):
    		i = str(i)
    		f.write(i)
    		f.write('
    ')
    	os.chdir('/Users/markzhang/Desktop/')
    	os.rename('io.txt',current_time())
    
  • 相关阅读:
    Repeater嵌套,增删改查综合运用
    DataSet用法(三) 操作数据
    创建DataSet
    DataSet用法(一)
    DataSet使用方法
    DataSet用法(二)
    Repeater嵌套绑定Repeater
    DataBinder.Eval用法
    简单谈谈DataSet与DataTable的区别
    Repeater嵌套的两种方案
  • 原文地址:https://www.cnblogs.com/mark-zh/p/10320285.html
Copyright © 2020-2023  润新知