【python:打开文件,编辑一行,将其保存为同一文件】教程文章相关的互联网学习教程文章

编写一个Python程序,从控制台输入一个字符串(保存在变量S中),然后通过while循坏不断输入字符串(保存在变量substr中),并统计substr在s中出现的次数,然后利用format方法格式化统计结果。【代码】

s = input("请输入一个字符串:") while True:subStr = input("请输入另一个字符串")if subStr == "exit":break;i = 0count = 0while i < len(s):j = s.find(subStr,i)if j > -1:count +=1i = j + len(subStr) else:break;print("‘‘{}‘在‘{}‘中出现了‘{}‘次".format(subStr,s,count))原文:https://www.cnblogs.com/ppystudy/p/12111020.html

python的序列化与反序列化(例子:dict保存成文件,文件读取成dict)【代码】

dict保存成文件(对象序列化)d = dict(name=‘TSQ‘, age=18)import pickle with open("dict.file", "wb") as f:pickle.dump(d, f)文件读取成dict(文件反序列化)d = {}import pickle with open("dict.file", "rb") as f:d = pickle.load(f)print(d)print(d)的结果是{‘name‘: ‘TSQ‘, ‘age‘: 18} 原文:https://www.cnblogs.com/taoshiqian/p/9771786.html

python模拟Get请求保存网易歌曲的url【图】

python模拟Get请求保存网易歌曲的url作者:vpoet日期:大约在夏季#coding:utf-8import requests import jsonurl = 'http://music.163.com//api/dj/program/byradio?radioId=271002&id=271002&ids=%5B%22271002%22%5D&limit=100&offset=0'headers = {'Host': 'music.163.com','Proxy-Connection': 'keep-alive','User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0....

自动播放视频并录屏保存的python脚本

`from time import sleep from selenium import webdriver from selenium.webdriver.firefox.webdriver import WebDriver from selenium.webdriver.support.ui import Select, WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By import pyautogui import pyperclipdriver = webdriver.Firefox()打开网页driver.get(‘https://www.luffycity.com/‘)登...

python爬取网页图片并保存到本地【代码】【图】

先把原理梳理一下:首先我们要爬取网页的代码,然后从中提取图片的地址,通过获取到的地址来下载数据,并保存在文件中,完成。下面是具体步骤:先确定目标,我挑选的是国服守望先锋的官网的英雄页面,我的目标是爬取所有的英雄的图片页面是这样的 首先做的就是得到它的源代码找到图片地址在哪里这个函数最终会返回网页代码def getHtml(url):html = requests.get(url)return html.text将其先导入文本文件观察 发现图片的地址所在...

Python面向对象编程指南(第9章)序列化和保存-JSON、YAML,PickleCSV和XML【代码】

把这本压箱底的书拿出来看了下,感觉还不错,就给自己记录一下。JSON,YAML,Pickle,XML和CSV比较适合用于数据交换,主要应用于单一对象而非多个对象的场景。Shelve支持多个对象的持久化为了存储Python中的对象,必须先将其转换为字节,然后再将字节写入文件,这个过程成为序列化,又要数据转化,压缩,编码。这是一本好书,超级烂的翻译,很多文字描述语句都读不通。9.3定义用于持久化的类。书中定义了类,通过jinja2来渲染实例。代...

Python,使用pandas保存数据为csv格式的文件【代码】

使用pandas对数据进行保存时,可以有两种形式进行保存   一、对于数据量不是很大的文件,可以放到列表中,进行一次性存储。  二、对于大量的数据,可以考虑一边生成,一边存储,可以避免开辟大量内存空间,去往列表中存储数据。本人才疏学浅,只懂一些表面的东西,如有错误,望请指正! 下面通过代码进行说明 1import pandas as pd2 3 4class SaveCsv:5 6def__init__(self):7 self.clist = [[1,2,3], [4,5,6], [7,8,9...

四、Python系列——Pandas数据库写入数据并追加保存多个sheet--覆盖原excel表数据与不覆盖原excel表数据的情况【代码】【图】

1import pandas as pd 2import numpy as np 3 data1 = pd.DataFrame(np.arange(12).reshape((3, 4))) 4 data2 = pd.DataFrame(np.random.randn(1, 2)) 5 data3 = pd.DataFrame(np.random.randn(2, 3)) 6 data4 = pd.DataFrame(np.random.randn(3, 4))View Code--该代码是后续内容所使用到的数据。使用Pandas数据库对Excel文件进行写入并保存--追加并保存多个sheet时覆盖原excel表数据与不覆盖的情况# 1.使用文件.to_excel ---覆盖原...

Python脚本读取Chrome浏览器保存的网站密码【代码】

#coding:utf-8import os import sys import sqlite3 import win32cryptdirectory_path = r‘Google\Chrome\User Data\Default\Login Data‘ file_path=os.path.join(os.environ[‘LOCALAPPDATA‘],directory_path) conn=sqlite3.connect(file_path) cursor = conn.cursor() cursor.execute(‘select username_value, password_value, signon_realm from logins‘) for data in cursor.fetchall():passwd = win32crypt.CryptUnprote...

Python实例之抓取网易云课堂搜索数据(post方式json型数据)并保存为TXT【代码】

本实例实现了抓取网易云课堂中以‘java’为关键字的搜索结果,经详细查看请求的方式为post,请求的结果为JSON数据具体实现代码如下:import requests import json finalstr = ‘‘#初始化字符串 totlePage = 0 #初始化总页数 test = 0 #初始化数据总条数 url = ‘http://study.163.com/p/search/studycourse.json‘ headers = {‘content-type‘: ‘application/json‘}def getD...

python3.5读取网页代码,并保存【代码】

在旧版的python中有个urllib模块,内有一个urlopen方法可打开网页,但新版python中没有了,新版的urllib模块里面只有4个子模块(error,request,response,parse),urlopen方法位于request子模块下。from urllib import requesturl = "http://www.163.com"#网页地址 wp = request.urlopen(url) #打开连接 content = wp.read() #获取页面内容 fp = open("a1.txt","w+b") #打开一个文本文件 fp.write(content) #写入数据 fp.close() #关...

Python连接数据库查询结果保存excl

pymysql------操作mysql数据库openpyxl------操作excel表 连上mysql操作:1、打开数据库import pymysqldb=pymysql.connect(host,user,password,database)2、使用cursor()方法创建一个游标对象cursor=db.cursor()3、执行操作a、数据库插入 try:  curcor.excute(sql)  db.commit()except:  db.rollback()b、数据库查询(fetchone()--该方法获取下一个查询结果集。结果集是一个对象、fetchall()-----接收全部的返回结果行.)cu...

python 保存网页为pdf到本地【代码】

1import urllib22import cookielib3import pdfkit4 5 cj = cookielib.LWPCookieJar()6 opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))7 urllib2.install_opener(opener)8 url = "https://www.taobao.com/" 9 req = urllib2.Request(url) 10‘‘‘ 保存html到本地‘‘‘11 operate = opener.open(req) 12 msg = operate.read() 13 document = ‘D://1.html‘14 file_ = open(...

python保存二维列表到txt文件,读取txt文件里面的数据转化为二维列表【代码】

源码:# 读文件里面的数据转化为二维列表def Read_list(filename):file1 = open(filename+".txt", "r")list_row =file1.readlines()list_source = []for i in range(len(list_row)):column_list = list_row[i].strip().split("\t") # 每一行split后是一个列表list_source.append(column_list) # 在末尾追加到list_source file1.close()return list_source#保存二维列表到文件def Save_list(list1,filename):fil...

python3爬虫初探(五)之从爬取到保存【代码】【图】

想一想,还是写个完整的代码,总结一下前面学的吧。import requests import re# 获取网页源码 url = ‘http://www.ivsky.com/tupian/xiaohuangren_t21343/‘ data = requests.get(url).text#正则表达式三部曲 #<img src="http://img.ivsky.com/img/tupian/t/201411/01/xiaohuangren-009.jpg" width="135" height="135" alt="卑鄙的我小黄人图片"> regex = r‘<img src="(.*?.jpg)"‘#匹配网址 pa = re.compile(regex)#转为pattern对...