文件操作
#文件打开
f = open('analyst.txt')
print(f)
#文件读取--字数
f.read(100)
#'https://www.zhipin.com/job_detail/eca7d86e080f55471nBy2tq_EFA~.html,数据分析工程师,15-30K·14薪,苏州 3-5年本科,ht'
#文件读取--按行
f.readline()
#'w.zhipin.com/job_detail/eca7d86e080f55471nBy2tq_EFA~.html,数据分析工程师,15-30K·14薪,苏州 3-5年本科,https://www.zhipin.com/gongsi/5655835880426ec51nN62t-0.html,同程艺龙,互联网已上市1000-9999人\n'
#按行读取
lines = f.readlines()
for each in lines:
print(each)
#每读取一行,文件指针便往后走,用tell查询读取位置
f.tell()
#重新调整指针位置,file.seek(需要的位置,0从头开始/1当前位置开始/2从文件末尾开始)
f.seek(20, 0)
line = f.readline()
print(line)
#om/job_detail/eca7d86e080f55471nBy2tq_EFA~.html,数据分析工程师,15-30K·14薪,苏州 3-5年本科,https://www.zhipin.com/gongsi/5655835880426ec51nN62t-0.html,同程艺龙,互联网已上市1000-9999人
#文件关闭
f.close()
#文件的写入
f = open('workfile.txt', 'wb+')
print(f.write(b'0123456789abcdef'))
print(f.seek(5))
print(f.read())
#16
#5
#b'56789abcdef'
#运行完自动关闭,节省内存
with open('workfile.txt') as f:
for each in f:
print(each)
#0123456789abcdef
OS模块
import os
#读取当前目录路径
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')
练习题
编写程序查找最长的单词
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)
网友评论