文件读取写入

优雅写法

  • open读取txt注意剔除换行符

    1. iplist = open("./ip.txt", "r", encoding='utf-8')
    2. for ip in iplist:
    3. agentId = self.ip_info_get(ip.strip('\n'))
    4. iplist.close()
  • json字符串在调用时,需要先将其加载,转化为json格式,

    1. data = json.loads(response)
  • with读取文件

    1. with open('复查结果.csv', 'w') as csvfile:
    2. writer = csv.writer(csvfile)
    3. # 写入首行
    4. writer.writerow(['ip', 'jar包', 'version', 'path'])
    5. for i in result:
    6. print(i)
    7. print(type(i))
    8. writer.writerow(['ip', i['name'], i['version'], i['path']])
    9. pass
  • 读取dict时直接选择key,如dict[‘data’],读取list时要选择角标,从0开始。

  • 处理文件名时,可以将敏感字符使用正则将其替换掉

    1. intab = r'[?*/\|.:><]'
    2. title = re.sub(intab, "", title)
    3. with open( title + '.html','w')as f:
    4. f.write(doc)
  • 读取xls文件,过滤掉首首行的写法

    1. # -*- coding:utf-8 -*-
    2. import xlrd
    3. data = xlrd.open_workbook('成分信息.xls') # 打开xls文件
    4. table = data.sheets()[0]
    5. nrows = table.nrows # 获取表的行数
    6. for i in range(nrows): # 循环逐行打印
    7. # 跳过第一行
    8. if i == 0:
    9. continue
    10. print (table.row_values(i))
  • 读取csv文件时去掉首行—-next()

    with open('探针.csv','r',encoding='utf-8') as list_file:
              reader = csv.reader(list_file)
              next(reader) # 跳过首行
              for row in csv.reader(list_file):
                  # print(row,type(row))
                  res = Check(row)
                  print(res,type(res))
                  writer.writerow(res)
    

HTTP 请求

  • requests时需要使用dict格式的cookies。

  • warnings.filterwarnings(“ignore”) ```python

warnings.filterwarnings(“ignore”) # 忽略Warning,针对SSL报错

requests.get(url=’https://‘ + url[1], headers=headers, verify=False, timeout=10)



<a name="Y5khN"></a>
# 传值

- 字符串传值时,如果有{},使用"{ip:{0}}".format(ip),会报错KeyError。只能用%s占位符,形如"{ip:%s}"%ip。



<a name="NhIYA"></a>
# 其它

- 异常捕获
```python
        try:
            requests.get(url='https://' + url[1], headers=headers, verify=False, timeout=10)
            result = url[0]+":"+ 'https://'+url[1]
            print("     " + result)
            return result
        except Exception as e2:
            result = url[0] + ":" + url[1]
            print("     " + result)
            print("     "+"抛出异常:%s" %e2)
            return result

js文件加载读取
https://zhuanlan.zhihu.com/p/269523443
execjs
参考:https://blog.csdn.net/weixin_39190897/article/details/108369314

with open("encrypt.js", "r", encoding="utf-8") as f:
             ctx = execjs.compile(f.read())
             self.password = ctx.call("encrypt", self.password)
             print('加密后的密码是:'+self.password)

环境依赖,nodejs
phamjs

写入 Excel

# 导入 xlwt 库
import xlwt

# 创建 xls 文件对象
wb = xlwt.Workbook()

# 新增两个表单页
sh1 = wb.add_sheet('成绩')
sh2 = wb.add_sheet('汇总')

# 然后按照位置来添加数据,第一个参数是行,第二个参数是列
# 写入第一个sheet
sh1.write(0, 0, '姓名')
sh1.write(0, 1, '专业')
sh1.write(0, 2, '科目')
sh1.write(0, 3, '成绩')

sh1.write(1, 0, '张三')
sh1.write(1, 1, '信息与通信工程')
sh1.write(1, 2, '数值分析')
sh1.write(1, 3, 88)

sh1.write(2, 0, '李四')
sh1.write(2, 1, '物联网工程')
sh1.write(2, 2, '数字信号处理分析')
sh1.write(2, 3, 95)

sh1.write(3, 0, '王华')
sh1.write(3, 1, '电子与通信工程')
sh1.write(3, 2, '模糊数学')
sh1.write(3, 3, 90)

# 写入第二个sheet
sh2.write(0, 0, '总分')
sh2.write(1, 0, 273)

# 最后保存文件即可
wb.save('test.xls')

读取 Excel

# 导入 xlrd 库
import xlrd

# 打开刚才我们写入的 test_w.xls 文件
wb = xlrd.open_workbook("test_w.xls")

# 获取并打印 sheet 数量
print( "sheet 数量:", wb.nsheets)

# 获取并打印 sheet 名称
print( "sheet 名称:", wb.sheet_names())

# 根据 sheet 索引获取内容
sh1 = wb.sheet_by_index(0)
# 或者
# 也可根据 sheet 名称获取内容
# sh = wb.sheet_by_name('成绩')

# 获取并打印该 sheet 行数和列数
print( u"sheet %s 共 %d 行 %d 列" % (sh1.name, sh1.nrows, sh1.ncols))

# 获取并打印某个单元格的值
print( "第一行第二列的值为:", sh1.cell_value(0, 1))

# 获取整行或整列的值
rows = sh1.row_values(0) # 获取第一行内容
cols = sh1.col_values(1) # 获取第二列内容

# 打印获取的行列值
print( "第一行的值为:", rows)
print( "第二列的值为:", cols)

# 获取单元格内容的数据类型
print( "第二行第一列的值类型为:", sh1.cell(1, 0).ctype)

# 遍历所有表单内容
for sh in wb.sheets():
    for r in range(sh.nrows):
        # 输出指定行
        print( sh.row(r))

修改 excel

# 导入相应模块
import xlrd
from xlutils.copy import copy

# 打开 excel 文件
readbook = xlrd.open_workbook("test_w.xls")

# 复制一份
wb = copy(readbook)

# 选取第一个表单
sh1 = wb.get_sheet(0)

# 在第五行新增写入数据
sh1.write(4, 0, '王欢')
sh1.write(4, 1, '通信工程')
sh1.write(4, 2, '机器学习')
sh1.write(4, 3, 89)

# 选取第二个表单
sh1 = wb.get_sheet(1)

# 替换总成绩数据
sh1.write(1, 0, 362)

# 保存
wb.save('test.xls')

https://mp.weixin.qq.com/s/8v7IsEM58dmGumbrPQRtdg

logging.info(“serial num is null”)
raw_dict = collections.OrderedDict()
raw_str = json.dumps(raw_dict, separators=(“,”, “:”))

�filename = url_unquote(filename, unsafe=b””)


�初始化写法:

class TSSHttpClient(object):
    def __init__(self, url_prefix=None, username=None, auth_uri=None, logout_uri=None):
          self.username = username or "tapadmin"
          self.url_prefix = url_prefix or 'https://{}:{}'.format("10.224.14.25", 443)
          self.auth_uri = auth_uri or "/skyeye/v1/admin/auth"
          self.logout_uri = logout_uri or "/skyeye/v1/admin/logout"
          self.init_secret()
          self.session = requests.Session()
          self.__login_process()

def wait(self):
sum = 10 # 设置倒计时时间
timeflush = 0.25 # 设置屏幕刷新的间隔时间
for i in range(0, int(sum / timeflush)):
list = [“\“, “|”, “/“, “—“]
index = i % 4
print(“\r程序正在运行 {}”.format(list[index]), end=””)
time.sleep(timeflush)