在Python中可以使用函數(shù)來對(duì)文件進(jìn)行操作薄嫡,具體使用方法:
使用open函數(shù)可以打開一個(gè)已存在的文件芋忿,或者創(chuàng)建一個(gè)新文件
open(文件名筷登,訪問模式)
f = open("test.txt","w")
- r—以只讀方式打開文件赵誓,文件的指針將會(huì)放在文件開頭傻盟,這是默認(rèn)模式活孩。
- w—打開一個(gè)文件只用于寫入物遇,如果該文件存在則將其覆蓋,如果不存在則創(chuàng)建新文件。
- a—打開一個(gè)文件用于追加询兴。
使用close函數(shù)關(guān)閉文件
close()
f.close()
文件的讀寫
寫數(shù)據(jù)
使用write( )向文件中寫入數(shù)據(jù)
f = open("test.txt","w")
f.write('hello world')
f.close()
使用read讀單個(gè)長(zhǎng)度
f = open ("test.txt",'r')
content = f.read(3)
print(content)
f.close()
使用readline讀一行
f = open("test.txt",'r')
content = f.readline()
print('1:%s'%content)
f.close()
使用readlines讀所有行
f = open('test.txt','r')
content = f.readlines()
print(content)
文件的重命名乃沙、刪除
要實(shí)現(xiàn)這個(gè)功能需要導(dǎo)入python中的os模塊
重命名文件,使用該函數(shù)中的rename()函數(shù)
import os
os.rename('王者榮耀.txt','王者榮耀終極版.txt')
刪除文件诗舰,使用該函數(shù)中的remove()函數(shù)
impost os
os.remove('王者榮耀.txt')
文件夾的相關(guān)操作
創(chuàng)建文件夾
impost os
os.mkdir('老王')
獲取當(dāng)前目錄
impost os
os.getcwd()
改變默認(rèn)目錄
impost os
os.chdir('../')
獲取目錄列表
impost os
os.listdir('./')
刪除文件夾
impost os
os.rmdir('老王')
文件操作.png