使用:os模块,ospase模块
打印当前路径
在当前路径创建tist目录
在test目录下创建test.txt文档
编test.tst文档,插入hello word
删除test。tst文档
删除test目录
# 引入模块
import os
import shutil
def opentxt(testFile):
with open(testFile, "w") as f:
f.write("hello word!")
print('.txt为空,已写入helloword!')
def closetxt(testFile):
open(testFile, 'w').close()
print('.txt错误内容已清空')
def gettxt(testFile):
with open(testFile, "r") as f: # 打开文件
text = f.read() # 读取文件
return text
def mkdir(path, txtPath):
# 去除首位空格
path = path.strip()
# 去除尾部 \ 符号
# path = path.rstrip("\\")
# 判断路径是否存在
# 存在 True
# 不存在 False
isExists = os.path.exists(path)
print('打印当前路径:' + path)
# 判断结果
if not isExists:
# 如果不存在则创建目录
os.makedirs(path) # 创建目录操作函数
print('test文件不存在,test文件已创建成功')
return True
else:
# 如果目录存在则不创建,并提示目录已存在
print('test文件已存在')
# .txt文档路径
testFile = path + '\\' + txtPath
# 判断txt文件是否存在
if os.access(testFile, os.F_OK):
print('.txt已存在')
# 读取txt文件内容
text = gettxt(testFile)
# txt内容为空
if not text:
# 写入hello word
opentxt(testFile)
# txt内容不为空
else:
if text == 'hello word!':
print('.txt内容为:' + text)
# 如果txt内容不是hello word!清空内容,写入hello word!
else:
print('.txt文本内容错误')
# 清空文本内容
closetxt(testFile)
# 写入hello word
opentxt(testFile)
else:
print('.txt不存在')
# 创建txt文件
file = open(testFile, 'w')
file.close()
print('.txt已创建')
# with
# path文件路基
# testFile文本路径
def removetxt(testFile):
os.remove(testFile)
print('.txt文件已删除')
def deletetxt(path, testFile):
# .txt存在
if os.access(testFile, os.F_OK):
print('.txt存在')
# 读取txt文件内容
text = gettxt(testFile)
# txt内容为空
if not text:
print('.txt内容为空')
else:
# 清空txt内容
closetxt(testFile)
# 删除test.txt文档
removetxt(testFile)
else:
print('.txt不存在')
# 删除test文件
if os.path.exists(path): # 如果文件存在
if (os.path.exists(path) == True):
shutil.rmtree(path)
print('test文件已删除')
else:
print('test文件不存在')
if __name__ == '__main__':
# 定义要创建的目录
mkpath = r"C:\\Users\\86183\\Desktop\\项目\\周二作业\\test"
# 定义要创建的txt文档
txtPath = 'text' + '.txt'
# 创建文件夹
mkdir(mkpath, txtPath)
# 删除
# testFile = mkpath + '\\' + txtPath
# deletetxt(mkpath, testFile)