Python基础之文件、目录

1.文件操作。

(1)文件创建。

(2)文件读取。

(3)文件重命名。

(4)文件删除。

2.目录操作。

(1)目录创建。

(2)目录删除。

He.py

#coding=utf8

import os

#创建文件 
def writeFile(fileName,str):
    fs=open(fileName,"w+")
    fs.write(str)
    fs.close()
    print("文件"+fileName+"创建成功")

#读取文件内容
def readFile(fileName):
    fs=open(fileName,"r+")
    str=fs.read()
    print("文件内容:"+str)

#删除文件
def removeFile(fileName):
    os.remove(fileName)
    print("文件"+fileName+"删除成功")

#文件重命名
def reNameFile(oldFileName,newFileName):
    os.rename(oldFileName,newFileName)
    print("文件"+oldFileName+"更改名字成功")

#创建目录
def createDir(dirName):
    os.mkdir(dirName)
    print("文件目录"+dirName+"创建成功")

#删除目录
def removeDir(dirName):
    os.rmdir(dirName)
    print("文件目录"+dirName+"删除成功")

调用代码:

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> from He import *
>>> writeFile("a.txt","hello tom welcome")
文件a.txt创建成功
>>> readFile("a.txt","b.txt")
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
readFile("a.txt","b.txt")
TypeError: readFile() takes 1 positional argument but 2 were given
>>> readFile("a.txt")
文件内容:hello tom welcome
>>> reNameFile("a.txt","b.txt")
文件a.txt更改名字成功
>>> removeFile("b.txt")
文件b.txt删除成功
>>> createDir("aa")
文件目录aa创建成功
>>> removeDir("aa")
文件目录aa删除成功
>>>
原文地址:https://www.cnblogs.com/joyet-john/p/7077491.html