#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:Erik Chan
# datetime:2018/12/27 9:29
# software: PyCharm
import os
# 獲取當前文件的父目錄文件夾
DIR = os.path.dirname(os.path.abspath(__file__))
cwd = os.getcwd() #獲取當前目錄即dir目錄下
print(cwd)
# 創建添加一個文件
f = open(DIR+"/test.txt","w",encoding='UTF-8')
# 寫入文件
str = '''
漢家三十六將軍
東方雷動橫陣云
雞鳴函谷客如霧
貌同心異不可數
赤丸夜語飛電光
徼巡司隸眠如羊
當街...
'''
f.write(str)
f.flush()# 強制寫入硬盤
f.close()# 關閉文件
# 打開當前文件
with open(DIR+"/poem.txt",'r',encoding='UTF-8') as file:
# 遍歷文件
for line in file:
print(line)# 打印文件內容
print(file.read())
print(file.readline())# 讀取一行
print(file.readlines())# 讀取多行,返回一個列表
# 修改文件
old_str = '將軍'
new_str = '帥士'
data = ''
with open(DIR+"/poem.txt",'r',encoding='UTF-8') as file:
for line in file:
if old_str in line:
line = line.replace(old_str,new_str)
data += line
with open(DIR+"/poem.txt",'w',encoding='UTF-8') as file:
file.write(data)
# 刪除文件內容
f = open(DIR+"/test.txt","w",encoding='UTF-8')
del f
# 刪除本地文件
os.remove(DIR+"/test.txt")