python常用代码

输入输出

str1 = raw_input("请输入:") # 返回一个字符串,没有换行符
str2 = input("请输入:")     # 可以接收一个Python表达式
print(str1, str2)
print("%s %s" % (str1, str2))
print("{} {}".format(str1, str2))

导入包

import sys
print(sys.argv)

读写文件(txt)

一般格式

with open("xxx", "r", encoding="utf-8") as fr:  # 读,"a"是追加,"+"可读可写
    for line in fr:
        # ...

with open("xxx", "w", encoding="utf-8") as fw:  # 写
    # ...

json格式

import json
with open("xxx", "r", encoding="utf-8") as fr:  # 读
    data = json.loads(fr.read())

with open("xxx", "w", encoding="utf-8") as fw:  # 写
    json.dump(json_obj, fw, ensure_ascii=False, indent=4)
    fw.write(json.dumps(json_obj, ensure_ascii=False, indent=4) + "\n") # 或

文件/文件夹操作

import os
path = os.getcwd() # path = "."
file_list = os.listdir(path)
for file in file_list:
    file_path = os.path.join(path, file)

os.path.isdir(file_path):   # ... 是目录?
os.path.isfile(file_path):  # ... 是文件?
os.remove(file_path) # 删除文件
os.removedirs(dir)   # 删除多个目录file_path
os.rename(old, new)  # 重命名
os.path.exists(dir)  # 判断文件/目录是否存在
os.makedirs(dir)     # 多层创建目录
os.makedir(dir)      # 创建一层目录

时间日期

import time
localtime = time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime())
print(localtime)  # 2020-04-19-13-59-46

word文档操作

读取word文档

import docx
doc = docx.Document("文件名.docx")
para = doc.paragraphs[1]

操作word文档

#coding: utf-8
from docx import *
from docx.shared import Inches
 
# 创建一个已存在的 word 文档的对象
file = Document()
 
# 添加标题,标题级别设置为2级
file.add_heading('添加标题',level=2)
 
# 添加段落
paragraph = file.add_paragraph('这是新增的段落')
paragraph.add_run('加粗').bold = True
paragraph.add_run('这是斜体').italic = True
 
# 添加表格
table = file.add_table(rows=2, cols=2)
# 添加表格内容,也可用: table.rows[0].cells[0].text = "第一行第一列"
#               或者用: table.cell(0,0).text = "cell_00"
for i in range(2):
    for j in range(2):
        cell = table.cell(i, j)
        cell.text = "第"+str(i+1) +"行第"+str(j+1) +"列"
 
# 添加图片,图片是当前文件夹下的 img.png 图片
file.add_picture('img.png',width=Inches(4.0))
 
# 保存新创建的 word 文档
file.save('testDoc.docx')

excel表格操作

读取excel表格

import pandas as pd
file_name = 'xxx.xlsx'
df = pd.read_excel(file_name, sheet_name='Sheet1') 

操作excel表格

链接: Pandas——掌握DataFrame的常用操作

正则表达式

链接: 菜鸟教程:Python3 正则表达式

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值