【Python】Python实用代码片段_脚手架

网络例子很多,但或大或小,亦或繁琐,不易看懂,也无法抽离复用。

此均个人实践后,将原子化的代码片段,记录于此。日后简单拼接,更为实用。

 

以下如未特殊说明,所有命令均是在CMD窗口内执行。

 

创建:2020年4月5日。

更新:2021年3月30日。

 

6. 调用bat文件

简单用法:

这里的 os.chdir(dir) 函数的意思是设置 dir 为当前工作文件夹,dir 最好设定为 bat文件 所在的文件夹。假如无此设定,若你的bat依赖某个环境变量,该bat是无法正常工作的。建议加上此函数。

import os

os.chdir("D:\\xxx\\yyy\\")            #此行非常重要
os.system("D:\\xxx\\yyy\\otr.bat")

复杂用法,参考此文

from subprocess import Popen, PIPE, STDOUT
import os

os.chdir(fold_address)

p = Popen("cmd.exe /c" + fold_address+bat_name, stdout=PIPE, stderr=STDOUT)

curline = p.stdout.readline()
# b''或 ''
while (curline != b''):
   print(curline)
   curline = p.stdout.readline()

p.wait()
print(p.returncode)

 

5. 获取CMD命令的输出

import os,sys

cmd = 'ping www.baidu.com'
cmdRst = os.popen(cmd)
text = cmdRst.read()
cmdRst.close()

print(text)

 

4. 读取CSV文件

# readCSV.py
# python 3.8

import csv

file = 'D:\\1.csv'

with open(file) as f:
	reader = csv.reader(f)
	header_row = next(reader)
	print(header_row)

	first_row = next(reader)
	print(first_row)

 

3. Python离线安装第三方库

3.1 联网机器上——安装库

先在联网机器上安装库 xxx

pip install xxx -i https://pypi.tuna.tsinghua.edu.cn/simple

3.2 联网机器上——生成库清单

pip freeze > D:\myneed.txt

3.3 联网机器上——编辑库清单

myneed.txt 中是所有已经通过 pip 安装的库,我们要删除不需要的,只保留这次依赖的库。

使用命令: pip show xxx  来查看其中的 Requires: aaa,bbb,ccc。我们将 myneed.txt 中的 aaa,bbb,ccc 保留下来,其它的都删除。

3.4 联网机器上——转存库文件

pip download -r D:\myneed.txt -d D:\mypkg

3.5 复制

将 D:\mypkg 和 D:\myneed.txt 复制到 离线机器上。

3.6 离线机器——安装

pip install --no-index --find-links=D:\mypkg -r D:\myneed.txt

如果安装时出现权限问题,请以管理员身份打开CMD窗口。

 

2 更换pip源到国内镜像

2.1 pip国内的一些镜像

  阿里云 https://mirrors.aliyun.com/pypi/simple/
  中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
  豆瓣(douban) http://pypi.douban.com/simple/
  清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
  中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/

2.2 修改源方法:

临时使用

可以在使用pip的时候在后面加上-i参数,指定pip源
eg: pip install scrapy -i https://pypi.tuna.tsinghua.edu.cn/simple

永久修改

linux:
修改 ~/.pip/pip.conf (没有就创建一个), 内容如下:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

windows:
直接在user目录中创建一个pip目录,如:C:\Users\xx\pip,新建文件pip.ini,内容如下:

[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple

亲测有效。此部分内容转自:https://blog.csdn.net/chenghuikai/article/details/55258957

 

1 目录及文件操作

1.1 遍历多层级目录 os.walk()

'''
注意:自带递归,无限遍历。每次的 root 均代表当前目录,files 代表当前目录下的全部文件
dirs 代表当前目录下的全部目录。
'''
import os
path = r'c:\code\py'

for root, dirs, files in os.walk(path):
	for name in files:
		print(os.path.join(root, name))

	for name in dirs:
		print( os.path.join(root, name))

1.2 正则表达式替换多行文本 re.sub()

比 str.replace(re_patten, string) 更强大的字符串正则替换。

1. re.sub() 详细参数解释参考见此,官网英文函数说明见此

2. 简洁全面的正则表达式介绍。

3. Python官网正则表达式的说明:Regular Expression Syntax

# 使用 re.sub 正则表达式进行多行替换

import re

inputStr = '''
	<tag>
		<hello>
			<this is a string>
		</hello>
	</tag>
	'''

''' 替换 hello 标签及子元素 '''
# 更严谨的做法 
pattern = re.compile(r'<hello>.*</hello>' ,re.S)
# 不太严谨的做法: pattern = r'<hello>.*\n.*\n.*</hello>'   
newTxt = r'<hello class="456"></hello>'
rst = re.sub(pattern, newTxt, inputStr)
print(rst)

'''
输出:
	<tag>
		<hello class="456"></hello>
	</tag>
'''

'''
警告:
若后面多次出现 <hello> </hello>,
该正则会从第一个<hello>一直匹配到最后一个 </hello>
请注意。
'''


正则表达式简单说明:

若需要 . 匹配 换行符,需要使用 re.S 模式,即
pattern = re.compile(r'<hello>.*</hello>' ,re.S)

此方法更为严谨,无论 hello 标签内含有多少行内容,均可符合 正则条件。

而 pattern = r'<hello>.*\n.*\n.*</hello>'   则比较死板,当出现 hello 标签内部元素不止一行时,便会出错。


.* 的 . 表示该行的任意字符,* 表示任意多个;\n 表示换行符。
<hello>.*\n.*\n.*</hello>  这个正则模式的含义就是要找到符合以下要求的内容:
<hello> + 该行后面的所有任意字符 + 换行符 + 第二行的所有任意字符 + 第二行换行符 + 第三行的前面所有任意字符 直到 </hello>。

 

 

import re

inputStr = '''
	<tag>
		<hello>
			<this is a string>
		</hello>
	</tag>
	'''

'''仅替换 <this is a string> 中的 string 为 newstr'''

pattern = re.compile(r'(<hello>.*<this is a )string(>.*</hello>)', re.S)
newTxt = r'\g<1>newstr\g<2>'
rst = re.sub(pattern, newTxt, inputStr)
print(rst)


'''
输出是:

	<tag>
		<hello>
			<this is a newstr>
		</hello>
	</tag>
	
'''

正则表达式简单说明:
pattern 中的 括号表示分组捕获,多个括号自动从1分组,可交由 替换串(参数2 newTxt) 索引使用,用于保留 被替换串 的部分内容。
newTxt 中的 \g<1> 表示输出捕获的第1个分组(即pattern中的第一个括号内容),\g<2>表示输出捕获的第2个分组(即pattern中的第二个括号内容)

简单理解方法:先把pattern用正则表达式表示出来,再把需要留用的内容用括号括起来。

re.sub() 共有5个参数。其中三个必选参数:pattern, repl, string;两个可选参数:count, flags。可自查手册。

 

1.3 读取中文文本文件

建议使用 with 语法,省去手动 close() 文件,更安全。

f = open(filename, 'r', encoding='utf-8')
cnt = f.read()
f.close()

# 注意:必须加 encoding= ,否则参数不匹配报错
# 函数原型 open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

#-----------------------------------------------------------

'''
读取文件,建议使用 with 关键词,可自动关闭文件。
无需手动 close() 文件
'''
with open(filename, 'r', encoding='utf-8') as f:
    cnt = f.read()


参考:Python.org 函数 open() 说明

 

1.4 Python替换文件(部分)内容


f = open(filename, 'r+', encoding='utf-8')

cnt = f.read()

replaceTxt = cnt.replace(.....)

f.seek(0)        #指示符定位到文件开始
f.truncate()    #清空文件

f.write(replaceTxt)

# 注意:必须设置 seek(0),否则出现意想不到的错误。

若未设置seek(0),运行结果可能与预期不一致,参考此文

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

qilei2010

送我一张彩票中了平分

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值