1. 程式人生 > >python操作文件和目錄

python操作文件和目錄

hello range mark users 文件操作 open doc 顯示 ret

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())

python操作文件和目錄