输入输出
str1 = raw_input("请输入:")
str2 = input("请输入:")
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:
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()
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)
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)
word文档操作
读取word文档
import docx
doc = docx.Document("文件名.docx")
para = doc.paragraphs[1]
操作word文档
from docx import *
from docx.shared import Inches
file = Document()
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)
for i in range(2):
for j in range(2):
cell = table.cell(i, j)
cell.text = "第"+str(i+1) +"行第"+str(j+1) +"列"
file.add_picture('img.png',width=Inches(4.0))
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 正则表达式