一.文件操作
1.什么是文件?

image.png
以上這些就是一些文件。
2.文件的作用
不僅人的大腦會(huì)遺忘事情,計(jì)算機(jī)也會(huì)如此,比如一個(gè)程序在運(yùn)行過程中用了九牛二虎之力終于計(jì)算出了結(jié)果,試想一下如果不把這些數(shù)據(jù)存放起來,相比重啟電腦之后,“哭都沒地方哭了”
二.文件打的打開與關(guān)閉
1.打開文件
f = open("1.txt","w")
這是在python中,使用open函數(shù),可以打開一個(gè)已經(jīng)存在的文件,或者創(chuàng)建一個(gè)新文件
open
2.關(guān)閉文件
f = open("1.txt","w")
f.close()
三.文件的讀寫
1.寫數(shù)據(jù)
使用write()可以完成向文件寫入數(shù)據(jù)
f = open("1.txt","w")
f.write("我愛你中國")
f.close()
2.讀數(shù)據(jù)(read) 讀單個(gè)長(zhǎng)度
f = open("1.txt","w")
ontent = f.read(3)
print("*"*30)
content = f.read()
print(content)
f.close()
3.讀數(shù)據(jù)(readlines) 讀所有行
f = open('1.txt','r')
content = f.readlines()
print(type(content))
i=1
for temp in content:
print('%d:%s'%(i,temp))
i+=1
f.close()
4.讀數(shù)據(jù)(readline)讀一行
f = open('1.txt', 'r')
content = f.readline()
print("1:%s"%content)
content = f.readline()
print("2:%s"%content)
f.close()
四.文件的定位讀寫
1.獲取當(dāng)前讀寫的位置
# 打開一個(gè)已經(jīng)存在的文件
f = open("1.txt", "r")
str = f.read(3)
print "讀取的數(shù)據(jù)是 : ", str
# 查找當(dāng)前位置
position = f.tell()
print "當(dāng)前文件位置 : ", position
str = f.read(3)
print "讀取的數(shù)據(jù)是 : ", str
# 查找當(dāng)前位置
position = f.tell()
print "當(dāng)前文件位置 : ", position
f.close()
2.定位到某個(gè)位置
# 打開一個(gè)已經(jīng)存在的文件
f = open("1.txt", "r")
str = f.read(30)
print "讀取的數(shù)據(jù)是 : ", str
# 查找當(dāng)前位置
position = f.tell()
print "當(dāng)前文件位置 : ", position
# 重新設(shè)置位置
f.seek(5,0)
# 查找當(dāng)前位置
position = f.tell()
print "當(dāng)前文件位置 : ", position
f.close()
demo:把位置設(shè)置為:離文件末尾,3字節(jié)處
# 打開一個(gè)已經(jīng)存在的文件
f = open("1.txt", "rb+")
# 查找當(dāng)前位置
position = f.tell()
print "當(dāng)前文件位置 : ", position
# 重新設(shè)置位置
f.seek(-3,2)
# 讀取到的數(shù)據(jù)為:文件最后3個(gè)字節(jié)數(shù)據(jù)
str = f.read()
print "讀取的數(shù)據(jù)是 : ", str
f.close()
五.文件的重命名、刪除
1.文件重命名
import os
os.rename("1.txt","2.txt")
2.刪除文件
import os
os.remove("2.txt")
六.文件夾的相關(guān)操作
1.創(chuàng)建文件夾
import os
os.mkdir("dat.dat")
2.獲取當(dāng)前目錄
import os
os.getcwd()
3.改變默認(rèn)目錄
import os
os.chdir("../")
4.獲取目錄列表
import os
os.listdir("./")
5.刪除文件夾
import os
os.rmdir("dat.dat")