Python is an increasingly popular programming language not only because of its simplicity, but also because there are many off-the-shelf packages that you can call directly.

There are also plenty of gadgets in Python to make your Python work more efficiently.

1. Quick sharing

The HTTP server

SimpleHTTPServer is a Web server built into Python, shared using port 8000 and HTTP.

You can quickly set up HTTP services and shared services on any platform (Windows, Linux, MacOS) just by setting up python.

Python2 version:

python -m SimpleHTTPServer
Copy the code

Python3 version:

python -m http.server
Copy the code

The FTP server

FTP sharing requires third-party components. Run the following command to install FTP sharing:

PIP install pyftpdlib python -m pyftpdlib-p Port numberCopy the code

Access method: ftp://IP: port.

2. The decompression

Here’s how to unpack five compressed files using Python:.gz. tar.zip.rar

zip

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
import zipfile

# zipfile compression
z = zipfile.ZipFile('x.zip'.'w', zipfile.ZIP_STORED) Zipfile.zip_stored is the default argument
# z = zipfile.zipfile ('ss.zip', 'w', zipfile.zip_deflated) #
z.write('x2')
z.write('x1')
z.close()

# zipfile decompression
z = zipfile.ZipFile('x.zip'.'r')
z.extractall(path=r"C:UsersAdministratorDesktop")
z.close()
Copy the code

tar

import tarfile

# compression
tar = tarfile.open('your.tar'.'w')
tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log')
tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log')
tar.close()

# decompression
tar = tarfile.open('your.tar'.'r')
tar.extractall()  # You can set the decompression address
tar.close()
Copy the code

gz

Gz generally compresses only one file, all of which often work with other packaging tools. For example, you can use tar to package it as x.tar.gz and then compress it as x.tar.gz

Unzip gz, which is essentially reading out a single file, using Python methods such as the following:

import gzip
import os
def un_gz(file_name):
"""ungz zip file"""
    f_name = file_name.replace(".gz"."")
Get the name of the file
g_file = gzip.GzipFile(file_name)
Create a gzip object
open(f_name, "w+").write(g_file.read())
The #gzip object is opened with read() and written to the file created by open().
g_file.close()
# Close the gzip object
Copy the code

rar

Since RAR is usually used under Windows, additional Python package rarFile is required. Installation:

Python setup.py install
Copy the code

Extract:

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
import rarfile
import os
def un_rar(file_name):
"""unrar zip file"""
    rar = rarfile.RarFile(file_name)
if os.path.isdir(file_name + "_files") :pass
else:
        os.mkdir(file_name + "_files")
    os.chdir(file_name + "_files"):
    rar.extractall()
    rar.close()
Copy the code

3. PIP common operations

PIP is Python’s well-known package management tool and is essential for Python development.

The installation

Online installation

PIP install -r requirements.txt PIP install -r requirements.txtCopy the code

Local installation:

PIP install --use-wheel --no-index --find-links=wheelhouse/Copy the code

To find the package

PIP search < package name >Copy the code

Delete the package

PIP uninstall < package name > or PIP uninstall -r requirements.txtCopy the code

Viewing Package Information

PIP show PIP showCopy the code

Check whether package dependencies are complete

PIP checkCopy the code

View the list of installed packages

pip list
Copy the code

Export all installed packages

pip freeze requirements.txt
Copy the code

4. Conversion between string and Json

Turn json STR

import json
str = '{"name": "zyl", "age": "two"}'
p = json.loads(str)
print(p)
print(type(p))
Copy the code

Turn json STR

Dumps converts JSON objects to strings using the json.dumps method.

s = {'name':'zyl'.'age':'22'}
s = json.dumps(s)
Copy the code

5. Python reads Excel

steps

  • Install python’s official Excel library –> XLRD

  • Get Excel file location and read

  • Read the sheet

  • Reads the specified rows and COLs contents

The sample

"Have a problem and no one to answer it? We have created a Python learning QQ group: 857662006 to find like-minded friends and help each other. There are also good video tutorials and PDF e-books in the group. ' ' '
# -*- coding: utf-8 -*-
import xlrd
from datetime import date,datetime
def read_excel(a):

# file location

ExcelFile=xlrd.open_workbook(r'C:UsersAdministratorDesktopTestData.xlsx')

Get the target EXCEL sheet name

print ExcelFile.sheet_names()

# If there are multiple sheets, you need to specify the target sheet to read, such as sheet2

#sheet2_name=ExcelFile.sheet_names()[1]

# get sheet content 【 1. According to the index of sheet 2. According to sheet name.

#sheet=ExcelFile.sheet_by_index(1)

sheet=ExcelFile.sheet_by_name('TestCase002')

Print the name of the sheet, the number of rows, the number of columns

print sheet.name,sheet.nrows,sheet.ncols

Get the value of the entire row or column

rows=sheet.row_values(2)# third line of content

cols=sheet.col_values(1)# second column content

print cols,rows

Get cell content

print sheet.cell(1.0).value.encode('utf-8')

print sheet.cell_value(1.0).encode('utf-8')

print sheet.row(1) [0].value.encode('utf-8')

Print the cell content format

print sheet.cell(1.0).ctype

if__name__ =='__main__':

read_excel()
Copy the code

6. Python screenshots

Python screenshots function, Windows environment, need to use PIL library.

Installation:

pip install Pillow
Copy the code

Example:

from PIL import ImageGrab
bbox = (x1, y1, x2,y2 )
# x1: the x coordinate of the start screenshot; X2: y coordinate of the start screenshot; X3: x coordinate of the end screenshot; X4: y coordinate of the end screenshot
im = ImageGrab.grab(bbox)
im.save('as.png')The path to save the screenshot file
Copy the code

7. ipython

Finally, IPython is a powerful Python tool.

IPython supports automatic variable completion, automatic indentation, bash shell commands, and many built-in utilities and functions.

It’s a Python interactive shell for Humans, and you don’t want to use your native Python shell anymore.