概述:

 主要内容 python read write() 删除文件写 ;
 在'w'和'a'模式下,如果你打开的文件不存在,那么open()函数会自动帮你创建一个。

1、写入和读取文件

python 读写文件 删除文件_python

str= 'Python read write'
with open('read.txt',mode='w',encoding='utf-8') as f:
    f.write(str)

with open('read.txt',mode='r',encoding='utf-8') as f:
    print(f.read())

输出:

Python read write

2、追加文件 写文件内容

with open('demo.txt',mode='a',encoding='utf-8') as f:
    f.write('\n hello word\t')

with open('demo.txt',mode='r',encoding='utf-8') as f:
    print(f.read())

输出:

hello word!

3、

os.remove()删除文件。

os.rmdir()删除一个空目录。

shutil.rmtree()删除一个目录及其所有内容。

pathlib.Path.unlink()删除文件或符号链接。

pathlib.Path.rmdir()删除空目录。

 01 直接删除文件

import os
os.remove("abc.txt")

02 判断文件是否存在

(或者先判断一下文件是否存在,如果存在才执行删除,否则打印提示)

import os
if os.path.exists("demo.txt"):
  os.remove("demo.txt")
else:
  print("The file does not exist")

03 删除文件夹:
删除文件夹则使用rmdir模块,用于删除指定路径的目录,但目录必须是空,否则将报错

# !/usr/bin/python3
import os, sys

os.chdir("d:\\tmp")

# listing directories
print ("the dir is: %s" %os.listdir(os.getcwd()))

# removing path
os.rmdir("newdir")

# listing directories after removing directory path
print ("the dir is:" %os.listdir(os.getcwd()))

04 彻底删除文件夹及其子文件方式

#coding:utf-8
import os
import stat
import shutil

#filePath:文件夹路径
def delete_file(filePath):
    if os.path.exists(filePath):
      for fileList in os.walk(filePath):
       for name in fileList[2]:
        os.chmod(os.path.join(fileList[0],name), stat.S_IWRITE)
        os.remove(os.path.join(fileList[0],name))
      shutil.rmtree(filePath)
      return "delete ok"
     else:
      return "no filepath"
     
    print os.path.exists("E:\\python\\demo")
    print delete_file("E:\\python\\demo")