文件操作
- 一、創建文件夾
- 二、文件操作模式
- 1.覆蓋寫入
- 2.讀取
- 3.追加
- 三、 Python腳本在文件中查找和替換文本
- 四、 python清空文件夾
一、創建文件夾
- 判斷文件或者文件夾是否存在
import ospath=r'D://測試文件夾'
if not os.path.exists(path):os.mkdir(path)print(os.path.exists(path))
二、文件操作模式
1.覆蓋寫入
file.close(file = open("test.txt", 'w')
#寫入內容
file.write("hellow word")
#關閉文件
file.close())
2.讀取
python中讀取文件的方法,read()
readlines()
file = open("test.txt", 'r')
#讀取文件內容
msg = file.read()
print(msg)
#關閉文件
file.close()
readlies()讀取文件內容,以列表
形式返回
file = open("test.txt", 'r')
#讀取文件內容
msg = file.readlines()
print(msg)
#關閉文件
file.close()
3.追加
在末尾文本之后,寫入
with open("test.txt", "a") as f:f.write("This is additional content.\n")
三、 Python腳本在文件中查找和替換文本
def find_replace(file_path, search_text, replace_text):with open(file_path, 'r') as f:text = f.read()modified_text = text.replace(search_text, replace_text)with open(file_path, 'w') as f:f.write(modified_text)
四、 python清空文件夾
import os
import stat
def del_files(path):for root, dirs, files in os.walk(path, topdown=False):print(root) # 各級文件夾絕對路徑print(dirs) # root下一級文件夾名稱列表,如 ['文件夾1','文件夾2']print(files) # root下文件名列表,如 ['文件1','文件2']# 第一步:刪除文件for name in files:os.chmod(os.path.join(root, name), stat.S_IWRITE) # 更改什么吊沒權限os.remove(os.path.join(root, name)) # 刪除文件# 第二步:刪除空文件夾for name in dirs:os.rmdir(os.path.join(root, name)) # 刪除一個空目錄path = "D://測試文件夾"
del_files(path)