码迷,mamicode.com
首页 > 编程语言 > 详细

python操作文件和目录

时间:2019-01-25 17:37:04      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:pen   rem   etc   文件   desktop   localtime   操作文件   top   imp   

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操作文件和目录

标签:pen   rem   etc   文件   desktop   localtime   操作文件   top   imp   

原文地址:https://www.cnblogs.com/mark-zh/p/10320285.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!