文件操作
#文件打開
f = open('analyst.txt')
print(f)
#文件讀取--字?jǐn)?shù)
f.read(100)
#'https://www.zhipin.com/job_detail/eca7d86e080f55471nBy2tq_EFA~.html,數(shù)據(jù)分析工程師,15-30K·14薪,蘇州 3-5年本科,ht'
#文件讀取--按行
f.readline()
#'w.zhipin.com/job_detail/eca7d86e080f55471nBy2tq_EFA~.html,數(shù)據(jù)分析工程師,15-30K·14薪,蘇州 3-5年本科,https://www.zhipin.com/gongsi/5655835880426ec51nN62t-0.html,同程藝龍,互聯(lián)網(wǎng)已上市1000-9999人\n'
#按行讀取
lines = f.readlines()
for each in lines:
print(each)
#每讀取一行冬筒,文件指針便往后走偎捎,用tell查詢讀取位置
f.tell()
#重新調(diào)整指針位置,file.seek(需要的位置,0從頭開始/1當(dāng)前位置開始/2從文件末尾開始)
f.seek(20, 0)
line = f.readline()
print(line)
#om/job_detail/eca7d86e080f55471nBy2tq_EFA~.html,數(shù)據(jù)分析工程師,15-30K·14薪,蘇州 3-5年本科,https://www.zhipin.com/gongsi/5655835880426ec51nN62t-0.html,同程藝龍,互聯(lián)網(wǎng)已上市1000-9999人
#文件關(guān)閉
f.close()
#文件的寫入
f = open('workfile.txt', 'wb+')
print(f.write(b'0123456789abcdef'))
print(f.seek(5))
print(f.read())
#16
#5
#b'56789abcdef'
#運(yùn)行完自動(dòng)關(guān)閉矢赁,節(jié)省內(nèi)存
with open('workfile.txt') as f:
for each in f:
print(each)
#0123456789abcdef
OS模塊
import os
#讀取當(dāng)前目錄路徑
os.getcwd()
#'C:\\Users\\Administrator\\python practice\\Data Whale'
#路徑中的所有文件
os.listdir()
#['.ipynb_checkpoints', 'analyst.txt', 'Day1.ipynb', 'Day2.ipynb', 'day7.ipynb']
#批量新建目錄
if os.path.isdir(r'.\b') is False:
os.mkdir(r'.\B')
os.mkdir(r'.\B\A')
#刪除空的文件夾
os.rmdir(r'.\B\A')
#重命名
os.rename('123.txt', '112233.txt')
練習(xí)題
編寫程序查找最長的單詞
def longest_word(filename):
with open(filename) as f:
length = 0
word = 'longest'
for each in f:
if len(each) > length:
length = len(each)
word = each
print(word)