合肥市建设厅官方网站谷歌浏览器引擎入口
合肥市建设厅官方网站,谷歌浏览器引擎入口,wordpress前台登录地址,注册公司流程及费用办公场所 上海Python 高效操作文件 与 HTML 网页基础入门 #xff08;2025–2026 实用写法#xff0c;适合有基础但想快速上手文件/网页处理的同学#xff09;
一、文件操作#xff08;推荐现代写法#xff09;
1. 文本文件最推荐的写法#xff08;with utf-8#xff09;
# 读取整…Python 高效操作文件 与 HTML 网页基础入门2025–2026 实用写法适合有基础但想快速上手文件/网页处理的同学一、文件操作推荐现代写法1. 文本文件最推荐的写法with utf-8# 读取整个文件小文件推荐withopen(data.txt,r,encodingutf-8)asf:contentf.read()# 一次性读完# 或linesf.readlines()# 按行读 → 列表# 或forlineinf:# 最省内存一行一行读print(line.strip())# 写入覆盖模式withopen(output.txt,w,encodingutf-8)asf:f.write(第一行\n第二行\n)f.writelines([第三行\n,第四行\n])# 追加模式日志最常用withopen(log.txt,a,encodingutf-8)asf:f.write(2026-03-03 新记录\n)2. 按行高效处理大文件推荐写法# 方法1最省内存一行一行处理不加载全部withopen(very_big.log,r,encodingutf-8)asf:forlineinf:ifERRORinline:print(line.strip())# 方法2使用 pathlibPython 3.5 更面向对象frompathlibimportPathfilePath(config.ini)textfile.read_text(encodingutf-8)# 读全部linesfile.read_text(encodingutf-8).splitlines()# 写入Path(newfile.txt).write_text(内容,encodingutf-8)3. CSV 文件最常用场景importcsv# 读取withopen(users.csv,r,encodingutf-8,newline)asf:readercsv.DictReader(f)# 推荐自动把首行当字段名forrowinreader:print(row[username],row[age])# 写入自动处理引号、逗号转义withopen(output.csv,w,encodingutf-8,newline)asf:writercsv.DictWriter(f,fieldnames[id,name,score])writer.writeheader()writer.writerow({id:1,name:小明,score:98.5})writer.writerows([{id:2,name:小红,score:92},{id:3,name:小刚,score:85}])4. JSON 文件API、配置文件最常用importjson# 读withopen(config.json,r,encodingutf-8)asf:datajson.load(f)# 直接得到 dict / list# 写自动格式化withopen(new_config.json,w,encodingutf-8)asf:json.dump(data,f,ensure_asciiFalse,indent2)5. 文件/目录常用操作pathlib 现代写法frompathlibimportPathimportshutil pPath(folder/subfolder/file.txt)print(p.exists())# 是否存在print(p.is_file())# 是文件吗print(p.is_dir())# 是目录吗print(p.parent)# 父目录print(p.name)# 文件名print(p.stem)# 不带扩展名的名字print(p.suffix)# .txt# 创建目录递归创建Path(logs/2026/03).mkdir(parentsTrue,exist_okTrue)# 复制文件 / 目录shutil.copy(source.txt,backup.txt)shutil.copytree(src_folder,dst_folder)# 删除小心# p.unlink() # 删除文件# p.rmdir() # 删除空目录# shutil.rmtree(folder) # 强制递归删除目录危险二、HTML 网页基础操作最常用三种方式1. requests BeautifulSoup爬虫/解析最经典组合importrequestsfrombs4importBeautifulSoup urlhttps://www.example.com/newsheaders{User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120}responserequests.get(url,headersheaders,timeout10)ifresponse.status_code200:soupBeautifulSoup(response.text,html.parser)# 常用提取方式titlesoup.title.string h1soup.find(h1).get_text(stripTrue)all_linkssoup.find_all(a)# CSS 选择器更强大news_itemssoup.select(div.news-item h2 a)foriteminnews_items:print(item.get_text(),item[href])else:print(请求失败,response.status_code)2. 保存网页为本地文件最简单静态保存# 方法1直接保存源码withopen(page.html,w,encodingutf-8)asf:f.write(response.text)# 方法2用 requests-html支持 JS 渲染需 pip install requests-htmlfromrequests_htmlimportHTMLSession sessionHTMLSession()rsession.get(https://dynamic-page.com)r.html.render(timeout20)# 等待 JS 执行print(r.html.html)# 渲染后的完整 HTML3. 快速生成简单 HTML模板 / 报表常用# 方法1字符串拼接小页面够用htmlf !DOCTYPE html html langzh head meta charsetUTF-8 title报告/title /head body h1数据统计 -{today}/h1 table border1 trth姓名/thth分数/th/tr trtd小明/tdtd98/td/tr /table /body /html withopen(report.html,w,encodingutf-8)asf:f.write(html)4. Jinja2 模板推荐报表、邮件、爬虫伪造页面# pip install jinja2fromjinja2importTemplate template_str h1欢迎 {{ name }}/h1 ul {% for item in items %} li{{ item }}/li {% endfor %} /ul tTemplate(template_str)htmlt.render(name张三,items[苹果,香蕉,橙子])withopen(welcome.html,w,encodingutf-8)asf:f.write(html)快速记忆口诀面试/日常常用文件操作小文件 →with open(..., r, encodingutf-8) as f: f.read()大文件 →for line in f:结构化数据 →csv.DictReader/json.load路径操作 → 用pathlib.Path网页操作静态页面 →requests.get() BeautifulSoup动态页面 →requests-html或selenium重生成 HTML → 字符串 / Jinja2需要我继续深入哪个方向Excel 操作pandas / openpyxlPDF 读写PyPDF2 / pdfplumber图片处理PIL / pillowrequests 高级用法代理、session、重试、异步BeautifulSoup 更复杂的选择器写法直接告诉我你最想学的部分