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('\n')
    os.chdir('/Users/markzhang/Desktop/')
    os.rename('io.txt',current_time())

猜你喜欢

转载自www.cnblogs.com/mark-zh/p/10320285.html