題目
請創建以學號命名的目錄,在該目錄中創建名稱爲file1.txt的文件,並將自己的個人信息(序號、姓名以及班級)等寫入該文件;然後並讀取文件中的內容到屏幕上;接着重新命名該文件爲file2.txt;,最後將其刪除。
分析題目中基本上有5個文件操作。
1、文件的創建
file = open(dir + 'file1.txt', 'w+')
2、文件的寫入
file.write('序號:1815925017\nname: xxx\nclass: java')
3、文件的讀取
str = file.readlines()
4、文件的重命名
os.rename(os.path.join(path, 'file1.txt'), os.path.join(path, 'file2.txt'))
5、文件的刪除
os.remove(path+ 'file2.txt')
實現代碼
import os
def file_operator(path):
if not os.path.exists(path):
os.makedirs(path) # 不存在目錄就創建
try:
# 打開文件 如果沒有就自動創建
file = open(path + 'file1.txt', 'w+')
# 寫入內容
file.write('序號:1815925017\nname: xxx\nclass: java')
# 文件指針恢復原先位置
file.seek(0)
# 讀取文件內容
str = file.readlines()
# 關閉文件
file.close()
# 打印文件裏的內容
print(str)
# 重命名
os.rename(os.path.join(path, 'file1.txt'), os.path.join(path, 'file2.txt'))
# 刪除
os.remove(path+ 'file2.txt')
except:
raise Exception('文件操作失敗...')
# 執行fileOper函數
file_operator('D:\\python_code\\1815925017\\')
運行結果