zoukankan      html  css  js  c++  java
  • 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())
    
  • 相关阅读:
    【模板】二分
    电脑桌面美化
    浪在ACM新春大作战
    【递归入门】组合+判断素数:dfs(递归)
    【递归入门】组合的输出:dfs
    01背包问题:DP
    [蓝桥杯][历届试题]回文数字
    洛谷 P1706 全排列问题 :STL / dfs
    【模板】DFS
    洛谷 P1781 宇宙总统:sort(string)
  • 原文地址:https://www.cnblogs.com/mark-zh/p/10320285.html
Copyright © 2011-2022 走看看