tongsiying

阅读|运动|自律

0%

python-accumulation

001-安装matplotlib

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
001-python怎么安装matplotlib
https://www.php.cn/python-tutorials-423909.html

1.进入到cmd窗口下
python -m pip install -U pip setuptools --proxy http://xzproxy.cnsuning.com:8080 -i https://pypi.tuna.tsinghua.edu.cn/simple/

2.接着键入进行自动的安装,系统会自动下载安装包。
python -m pip install matplotlib --proxy http://xzproxy.cnsuning.com:8080 -i https://pypi.tuna.tsinghua.edu.cn/simple/

3.安装完成后,可以用python -m pip list查看本机的安装的所有模块,确保matplotlib已经安装成功。
显示的界面为:
MarkupSafe 1.0
matplotiib 2.2.3
mistune 0.8.3
nbconvert 5.3.1
nbformat 4.4.0
notebook 5.4.0
munpy 1.14. 0
https://www.cnblogs.com/dingjiaoyang/p/11579723.html


linux安装:
yum install python-matplotlib.x86_64

002-博客

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
https://www.crifan.com/how_to_do_python_development_under_windows_environment/
https://www.runoob.com/numpy/numpy-matplotlib.html
https://blog.csdn.net/vs_hero_2019/article/details/88322515
https://www.cnblogs.com/OliverQin/p/8976150.html
https://blog.csdn.net/discoverer100/article/details/90111149
https://blog.csdn.net/beautiful77moon/article/details/96475964

https://pypi.org/project/configparser/#files

https://www.cnblogs.com/hanmk/p/9843136.html
https://www.cnblogs.com/feeland/p/4514771.html

https://www.cnblogs.com/clement-jiao/p/9043110.html

https://www.zhangshengrong.com/p/QrXejvyy1d/

003-Linux服务器没有GUI的情况下使用matplotlib绘图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
https://www.cnblogs.com/devilmaycry812839668/p/10201971.html

最近看到关于 python3 中用matplotlib 不进行交互画图,而是直接将图保存到硬盘,主要的一个设置就是  matplotlib.use('agg')
 
注明:
其实不设置  matplotlib.use('agg') 也可以把图片保存到硬盘,但是设置了这条语句再调用 matplotlib.pyplot.show 等进行交互式图片查看就会报错。
可以这么理解,设置了  matplotlib.use('agg') 后便强制你不能交互式查看显示图片,而只能保存到磁盘再查看。
 
 
下面对其进行一些介绍:
import matplotlib

matplotlib.use('Agg')

#而且matplotlib.use('Agg')必须添加在 import matplotlib.pyplot 之前,否则无效
import matplotlib.pyplot as plt


#最后在后面加上
plt.savefig('/tmp/figure_2_1.png')
#就可以把绘制的图存为png,down到本地查看就行了

003-读文件生成图表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# encoding: utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

file = open('map.txt') #打开文档
data = file.readlines() #读取文档数据
para_1 = [] #新建列表,用于保存第一列数据
para_2 = [] #新建列表,用于保存第二列数据
for num in data:
# split用于将每一行数据用逗号分割成多个对象
#取分割后的第0列,转换成float格式后添加到para_1列表中
para_1.append(float(num.split(',')[0]))
#取分割后的第1列,转换成float格式后添加到para_1列表中
para_2.append(float(num.split(',')[1]))
plt.figure()
plt.title('map')
plt.plot(para_1, para_2)
plt.savefig('./figure_2_1.png')

004-生成多张图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import matplotlib 
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from numpy import *
x=linspace(-2,2)
y1=2*x+1
y2=x**2

plt.figure()
plt.plot(x,y1)
plt.savefig('./1.png')

plt.figure()
plt.plot(x,y2,color='red',linestyle='--')

plt.savefig('./2.png'

005-读文件生成多张图

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# encoding: utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

file = open('map.txt') #打开文档
data = file.readlines() #读取文档数据
para_1 = [] #新建列表,用于保存第一列数据
para_2 = [] #新建列表,用于保存第二列数据
para_3 = []
for num in data:
para_1.append(float(num.split(',')[0]))
para_2.append(float(num.split(',')[1]))
para_3.append(float(num.split(',')[2]))

plt.figure()
plt.title('map')
plt.plot(para_1, para_2)
plt.savefig('./1.png')

plt.figure()
plt.plot(para_1, para_3)
plt.savefig('./2.png')
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# encoding: utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

file = open('map.txt') #打开文档
data = file.readlines() #读取文档数据
para_1 = [] #新建列表,用于保存第一列数据
para_2 = [] #新建列表,用于保存第二列数据
para_3 = []
para_4 = []
para_5 = []
para_6 = []
for num in data:
para_1.append(float(num.split(',')[0]))
para_2.append(float(num.split(',')[1]))
para_3.append(float(num.split(',')[2]))
para_4.append(float(num.split(',')[4]))
para_5.append(float(num.split(',')[5]))
para_6.append(float(num.split(',')[6]))

plt.figure()
plt.title('IOPS')
plt.plot(para_1, para_2)
plt.xlabel("second")
plt.ylabel("tims")
plt.figtext(0.75, 0.45, 'IOPS',
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)
plt.savefig('./1.png')

plt.figure()
plt.title('BW')
plt.plot(para_1, para_3)
plt.xlabel("second")
plt.ylabel("MB/sec")
plt.figtext(0.75, 0.45, 'BM',
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)
plt.savefig('./2.png')

plt.figure()
plt.title('RESP')
plt.plot(para_1, para_4)
plt.xlabel("second")
plt.ylabel("resp/time")
plt.figtext(0.75, 0.45, 'RESP',
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)
plt.savefig('./3.png')

plt.figure()
plt.title('READ-RESP')
plt.plot(para_1, para_5)
plt.xlabel("second")
plt.ylabel("read/resp")
plt.figtext(0.75, 0.45, 'READ-RESP',
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)
plt.savefig('./4.png')

plt.figure()
plt.title('WRITE-RESP')
plt.plot(para_1, para_6)
plt.xlabel("second")
plt.ylabel("write/resp")
plt.figtext(0.75, 0.45, 'WRITE-RESP',
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)
plt.savefig('./5.png')

006-函数生成图表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# encoding: utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

file = open('map.txt') #打开文档
data = file.readlines() #读取文档数据
para_1 = [] #新建列表,用于保存第一列数据
para_2 = [] #新建列表,用于保存第二列数据
para_3 = []
para_4 = []
para_5 = []
para_6 = []
for num in data:
para_1.append(float(num.split(',')[0]))
para_2.append(float(num.split(',')[1]))
para_3.append(float(num.split(',')[2]))
para_4.append(float(num.split(',')[4]))
para_5.append(float(num.split(',')[5]))
para_6.append(float(num.split(',')[6]))

def figure_show(a,x,y):
plt.figure()
plt.title(a)
plt.plot(x, y)
plt.xlabel("second")
plt.ylabel(a)
plt.figtext(0.75, 0.45, a,
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)

plt.savefig(a+".png")

figure_show('iops',para_1,para_2)

报错解决呀:

1
2
3
4
5
6
7
8
9
直接报错:TypeError: cannot concatenate 'str' and 'int' objects
解决这个方法只有提前把num转换为字符串类型,可以使用bytes函数把int型转换为string型。
代码:
# coding=utf8
str = '你的分数是:'
num82
numbytes(num)
text = str+num+'分 | 琼台博客'
print text

007 zip

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
看一个实例:
x = [1, 2, 3]
y = [-1, -2, -3] # y = [i * -1 for i in x]
zip(x, y)
zip的结果如下:
[(1, -1), (2, -2), (3, -3)]
zip([seql, ...])接受一系列可迭代对象作为参数,将对象中对应的元素打包成一个个tuple(元组),然后返回由这些tuples组成的list(列表)。

进入正题:如何使用一个for循环同时循环多个变量呢?使用tuple。如下,同时循环i和j变量。

for (i, j) in [(1, 2), (2, 3), (4, 5)]:
print(i, j)
输出结果如下:
(1, 2)
(2, 3)
(4, 5)
所以我们如果要将x和y中的元素分别相加,则可以使用如下代码:
for (i, j) in zip(x, y):
print(i + j)
输出结果:
0
0
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# encoding: utf-8
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

file = open('map.txt') #打开文档
data = file.readlines() #读取文档数据
para_1 = [] #新建列表,用于保存第一列数据
para_2 = [] #新建列表,用于保存第二列数据
para_3 = []
para_4 = []
para_5 = []
para_6 = []
for num in data:
para_1.append(float(num.split(',')[0]))
para_2.append(float(num.split(',')[1]))
para_3.append(float(num.split(',')[2]))
para_4.append(float(num.split(',')[4]))
para_5.append(float(num.split(',')[5]))
para_6.append(float(num.split(',')[6]))

def figure_show(a,x,y):
plt.figure()
plt.title(a)
plt.plot(x, y)
plt.xlabel("second")
plt.ylabel(a)
plt.figtext(0.75, 0.45, a,
fontsize=40, color='gray',
ha='right', va='bottom', alpha=0.4)

plt.savefig(a+".png")

name = ["iops","MB","resp","read-resp","write-resp"]
y = [para_2, para_3, para_4, para_5, para_6]
for (i, j) in zip(name, y):
figure_show(i,para_1,j)

008 用python执行Linux命令

1
2
3
4
https://www.cnblogs.com/Jintaonet/p/11158485.html
https://www.cnblogs.com/clhac/p/3708166.html
import subprocess
subprocess.call(["ls","-l"])

009 enumerate() 函数

1
2
3
4
5
6
7
>>>seq = ['one', 'two', 'three'] 
>>> for i, element in enumerate(seq):
... print i, element
...
0 one
1 two
2 three

010 换行写

1
2
3
with open("new.txt", "w") as f:
f.write("Hello World!"+"\n")
f.write("2"+"\n")

configparser python读配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
https://pypi.org/project/configparser/#files

https://www.cnblogs.com/hanmk/p/9843136.html
https://www.cnblogs.com/feeland/p/4514771.html

https://www.cnblogs.com/clement-jiao/p/9043110.html

https://zixuephp.net/article-431.html


https://blog.csdn.net/tadwork/article/details/80845599
今天把服务器上一个备份同步脚本放到老服务器上用,执行脚本后报错。
import configparser
ImportError: No module named configparser
pip安装configparser也没有,网上一查原来是python3的,对应python2的是ConfigParser。

修改代码

try:
import configparser
except:
import ConfigParser as configparser
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
[root@ceph4 vdench]# cat config.ini 
[mysql]
host = 127.0.0.1
port = 3306
user = root
password = Zhsy08241128
database = leartd
[root@ceph4 vdench]# cat 2.py
# -*- coding:utf-8 -*-
import os
#import ConfigParser
import ConfigParser

# 项目路径
rootDir = os.path.split(os.path.realpath(__file__))[0]
# config.ini文件路径
configFilePath = os.path.join(rootDir, 'config.ini')


def get_config_values(section, option):
"""
根据传入的section获取对应的value
:param section: ini配置文件中用[]标识的内容
:return:
"""
config = ConfigParser.ConfigParser()
config.read(configFilePath)
# return config.items(section=section)
return config.get(section=section, option=option)


if __name__ == '__main__':
result = get_config_values('mysql', 'port')
print(result)

以逗号分隔成列表

1
https://www.cnblogs.com/clement-jiao/p/9043110.html

python脚本传递参数

1
https://www.cnblogs.com/lijunjiang2015/p/7689492.html

python编译

1
python -m py_compile file.py

使用Matplotlib画图系列(一)

1
https://www.cnblogs.com/laoniubile/p/5893286.html
1
2
3
4
5
6
7
8
实现一个最简单的plot函数调用:

import matplotlib.pyplot as plt
y=pp.DS.Transac_open # 设置y轴数据,以数组形式提供
x=len(y) # 设置x轴,以y轴数组长度为宽度
x=range(x) # 以0开始的递增序列作为x轴数据
plt.plot(x,y) # 只提供x轴,y轴参数,画最简单图形
图形输出结果类似于:

img

1
2
3
加入新方法:
plt.figure() :自定义画布大小
plt.subplot() :设置画布划分以及图像在画布上输出的位置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import matplotlib.pyplot as plt
y=pp.DS.Transac_open # 设置y轴数据,以数组形式提供
x=len(y) # 设置x轴,以y轴数组长度为宽度
x=range(x) # 以0开始的递增序列作为x轴数据
#==============================
plt.figure(figsize=(8,8),dpi=80) # 画图之前首先设置figure对象,此函数相当于设置一块自定义大小的画布,使得后面的图形输出在这块规定了大小的画布上,其中参数figsize设置画布大小
plt.subplot(221) # 将figure设置的画布大小分成几个部分,参数‘221’表示2(row)x2(colu),即将画布分成2x2,两行两列的4块区域,1表示选择图形输出的区域在第一块,图形输出区域参数必须在“行x列”范围 ,此处必须在12之间选择——如果参数设置为subplot(111),则表示画布整个输出,不分割成小块区域,图形直接输出在整块画布上
plt.plot(y,xx) # 在2x2画布中第一块区域输出图形
plt.subplot(222)
plt.plot(y,xx) #在2x2画布中第二块区域输出图形
plt.show()
plt.subplot(223) #在2x2画布中第三块区域输出图形
plt.plot(y,xx)
plt.subplot(224) # 在在2x2画布中第四块区域输出图形
plt.plot(y,xx)
#==============================
plt.plot(x,y) # 只提供x轴,y轴参数,画最简单图形
输出结果:

img

1
2
3
加入新方法:
plt.xticks():设置x轴刻度的表现方式
plt.xlim():设置x轴刻度的取值范围
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt
import numpy as nu

y=pp.DS.Transac_open # 设置y轴数据,以数组形式提供

x=len(y) # 设置x轴,以y轴数组长度为宽度
x=range(x) # 以0开始的递增序列作为x轴数据

plt.figure(figsize=(8,8),dpi=80) # 画图之前首先设置figure对象,此函数相当于设置一块自定义大小的画布,使得后面的图形输出在这块规定了大小的画布上,其中参数figsize设置画布大小
plt.subplot(111) # 将figure设置的画布大小分成几个部分,参数‘221’表示2(row)x2(colu),即将画布分成2x2,两行两列的4块区域,1表示选择图形输出的区域在第一块,图形输出区域参数必须在“行x列”范围 ,此处必须在12之间选择——如果参数设置为subplot(111),则表示画布整个输出,不分割成小块区域,图形直接输出在整块画布上
plt.plot(y,x)
#================================
plt.xlim(0,1000) # 设置x轴刻度范围,从0~1000
plt.ylim(0,20) # 设置y轴刻度的范围,从0~20

plt.xticks(nu.linspace(0,1000,15,endpoint=True)) # 设置x轴刻度
plt.yticks(nu.linspace(0,20,10,endpoint=True)) # 设置y轴刻度
#numpy.linspace()方法返回一个等差数列数组,第一个参数表示等差数列的第一个数,第二个参数表示等差数列最后一个数,第三个参数设置组成等差数列的元素个数,endpoint参数设置最后一个数是否包含在该等差数列。数列中相邻元素间的步长值为随机
如:nu.linspace(0,1000,15,endpoint=True)表示:第一个元素为0,最后一个数为1000,在这个 范围内,取15个值,构成一个等差数列,步长值随机,且1000包含在该数列中
#================================
plt.show()
图形输出结果:

img

1
2
3
修改plot方法,新加入参数:
plt.plot(y,xx,color='red',linewidth=2.5,linestyle='-') # color参数设置曲线颜色,linewidth设置曲线宽度,linestyle设置曲线风格
输出结果:

img

matplotlib 横坐标为时间数据的设置

1
2
https://www.cnblogs.com/Lengjie/p/9377729.html
https://blog.csdn.net/zhangpeterx/article/details/83628558
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# -*- coding: utf-8 -*-

import numpy as np
import pandas as pd
from datetime import datetime
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


plt.rcParams['font.sans-serif']=['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False # 用来正常显示负号

fig=plt.figure(figsize=(12,6)) # 定义图并设置画板尺寸
fig.set(alpha=0.2) # 设定图表颜色alpha参数
# fig.tight_layout() # 调整整体空白
plt.subplots_adjust(bottom=0.06,top=0.94,left=0.08,right=0.94,wspace =0.36, hspace =0.5) # 设置作图范围、子图间距。

df_milano=pd.read_csv("milano_270615.csv") # 读取数据

x1= df_milano['day'].values # 自变量序列
x1= [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in x1] # 格式化时间数据输入
y1= df_milano['temp'] # 因变量序列
ax=fig.add_subplot(111) # 定义子图
plt.xticks(rotation=70) # 横坐标刻度旋转角度
ax.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S")) # 设置横坐标时间标签的格式
# ax.xaxis.set_major_locator(mdates.HourLocator()) # 指定横坐标刻度序列
ax.set_xticks(x1) # 指定横坐标刻度序列
ax.plot(x1,y1,'r') # 绘图

plt.show()

matp

1
2
https://www.cnblogs.com/magle/p/7389240.html
https://www.jianshu.com/p/33f843a7cef5

GET请求

https://blog.csdn.net/weixin_42734407/article/details/81162026

1
2
3
4
5
6
7
8
9
10
11
12
import urllib
import urllib2
import os
import json
url = "http://127.0.0.1:8787/region/pool?pretty=y&prefix=test"
req = urllib2.Request(url)
print req
res_data = urllib2.urlopen(req)
res = res_data.read()
print res

实现:curl -s -X GET "http://127.0.0.1:8787/region/pool?pretty=y&prefix=test"

pos请求

1
2
3
4
5
6
7
8
9
10
11
12

# -*- coding:utf-8 -*-
import requests

# 以下为POST请求
url = 'https://xxxxx.com/login'
postdatas = {'key': 'value'}
requests = requests.post(url, data=postdatas)
print requests.content # 返回字节形式


然后其他的put、delete等方法,也可以照葫芦画瓢的使用

响应码code和响应头headers的处理

1
2
3
4
5
6
7
8
9
10
11
# -*- coding:utf-8 -*-
import requests

url = 'https://www.csdn.net/'
r = requests.get(url)
if r.status_code == requests.codes.ok:
print '=== status_code === ', r.status_code # 响应码
print '=== headers === ', r.headers # 响应头
print '=== Content-Type === ', r.headers.get('Content-Type') # 获取响应头中的Content-Type字段
else:
r.raise_for_status() # 抛出异常

Python处理Json数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Python处理Json数据
获取json里的数据
获取其中所有dog的name:

{
"animals": {
"dog": [
{
"name": "Rufus",
"age":15
},
{
"name": "Marty",
"age": null
}
]
}
}
我们可以这样做:

load_data = json.loads(dump_data)
data = load_data.get("animals").get("dog")
result1 = []
for i in data:
result1.append(i.get("name"))
print(result1)
运行结果:

['Rufus', 'Marty']

python 生成随机字符串(数字+字母+特殊字符)

https://blog.csdn.net/u011921487/article/details/90522996

1
2
3
4
5
6
7
8
9
import random
import string
#第一种方法
seed = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@#$%^&*()_+=-"
sa = []
for i in range(8):
sa.append(random.choice(seed))
salt = ''.join(sa)
print salt

python生成随机数、随机字符串

https://www.cnblogs.com/zqifa/p/python-random-1.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
python生成随机数、随机字符串

import random
import string

# 随机整数:
print random.randint(1,50)

# 随机选取0到100间的偶数:
print random.randrange(0, 101, 2)

# 随机浮点数:
print random.random()
print random.uniform(1, 10)

# 随机字符:
print random.choice('abcdefghijklmnopqrstuvwxyz!@#$%^&*()')

# 多个字符中生成指定数量的随机字符:
print random.sample('zyxwvutsrqponmlkjihgfedcba',5)

# 从a-zA-Z0-9生成指定数量的随机字符:
ran_str = ''.join(random.sample(string.ascii_letters + string.digits, 8))
print ran_str

# 多个字符中选取指定数量的字符组成新字符串:
prin ''.join(random.sample(['z','y','x','w','v','u','t','s','r','q','p','o','n','m','l','k','j','i','h','g','f','e','d','c','b','a'], 5))

# 随机选取字符串:
print random.choice(['剪刀', '石头', '布'])

# 打乱排序
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
print random.shuffle(items)

获取当前路径

https://www.cnblogs.com/Jomini/p/8636129.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
一、获取当前路径
1、使用sys.argv[0]
import sys
print sys.argv[0]
#输出
#本地路径

2os模块
import os
print os.getcwd() #获取当前工作目录路径
print os.path.abspath('.') #获取当前工作目录路径
print os.path.abspath('test.txt') #获取当前目录文件下的工作目录路径
print os.path.abspath('..') #获取当前工作的父目录 !注意是父目录路径
print os.path.abspath(os.curdir) #获取当前工作目录路径

3、改变当前目录

1) 使用: os.chdir(path)。
比如, 如果当前目录在 ‘E:’ 下面, 然后进入E 下面的files 文件 可以使用 os.chdir(E:\files).
之后,使用比如 test1 = open('file1.txt'), 打开的文件会是在这个 ‘E:\files’ 目录下的文件,而不是 'E' 下的文件。

4、组合路径返回
os.path.join('file1','file2','file3')
合并得到路径 file1/file2/file3

>>> print os.path.join('E:', 'file1', 'file2')
E:/file1/file2
>>> print os.path.join('/home', '/home/file1/', '/home/file1/file2/')
/home/file1/file2/


no.2
import os
root = os.getcwd() #获得当前路径 /home/dir1
print root
#输出
#/home/dir1

name = "file1" #定义文件名字
print(os.path.join(root, name)) #合并路径名字和文件名字,并打印
#输出
#/home/dir1/file1

二、获得当前目录下所有文件

  1. os.walk() 用于在目录树种游走输出目录中的文件名字,向上或下;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    语法
    os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

    参数:
    top -- 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径,
    文件夹名字, 文件名】。

    topdown --可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。
    如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。

    onerror -- 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。

    followlinks -- 设置为 true,则通过软链接访问目录。
    1. 1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      import os
      root = os.getcwd()

      def file_name(file_dir):
      for root, dirs, files in os.walk(file_dir):
      print "-----------"
      print root #os.walk()所在目录
      print dirs #os.walk()所在目录的所有目录名
      print files #os.walk()所在目录的所有非目录文件名
      print " "

      file_name(root)

paramiko模块,基于SSH用于连接远程服务器并执行相关操作。

https://www.cnblogs.com/python-nameless/p/6855804.html

赞赏一下吧~