Python 文件操作

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

Python 中的文件模式

Character Meaning
'r' open for reading (default)

'w' open for writing, truncating the file first
    If file does not exist, it creates a new file.

'x' open for exclusive creation, failing if the file already exists

'a' open for writing, appending to the end of the file if it exists
    If file does not exist, it creates a new file.

'b' binary mode

't' text mode (default)

'+' open a disk file for updating (reading and writing)

'U' universal newlines mode (deprecated)

读取文件的全部内容

open("test.txt", mode="r", encoding='utf8').read()    

逐行读文件

filepath = 'test.txt'  
with open(filepath) as fp:  
    for cnt, line in enumerate(fp):
        print("Line {}: {}".format(cnt, line))

with open(filepath) as fp:
    for line in fp:
        print(line, end='')

向文件添加文本

filepath = 'test.txt'
with open(filepath, 'a') as wf:
    wf.write("hello world!\n")

"+"的应用

filepath = 'test.txt'
with open(filepath, 'a+') as wf:
    wf.write('hello, ')
    wf.seek(0)
    wf.write('world!') # If the file is opened for appending using either 'a' or 'a+', any seek() operations will be undone at the next write
    wf.seek(0)
    content = wf.read()
    print(content)

参考:

python open


Python

这篇文章: 有用 无用
创建 2018-08-05 23:11:01 / 更新 2018-10-16 19:17:41

Python 字典

如何创建一个字典:

phonebook = {'foo': '324234', 'bar': '234324'}

person = dict('name' = 'Noah', 'age' = 18)

paddle = dict([('VISCARIA', 'butterfly'), ('CLIPPER WOOD', 'sitiga')])

len(phonebook) # 返回键值对的数量 2

person['name'] # 'Noah'

person['name'] = 'David'

del phonebook['foo'] # 删除键值为'foo'的项

'bar' in phonebook # 检查phonebook中是否有键为'bar'的项   

如何利用zip创建一个字典:

>>> a = [1,2,3]
>>> b = ['a', 'b', 'c', 'd']
>>> zip(a, b)
<zip object at 0x109c60a48>
>>> list(zip(a, b))
[(1, 'a'), (2, 'b'), (3, 'c')]
>>> dict(zip(a,b))
{1: 'a', 2: 'b', 3: 'c'}

字典中键可以自动创建:

car = {}
car['brand'] = 'honda'

字典方法:

clear

d = {}
d['name'] = 'Moose'
d['age'] = 24
d.clear() # 清除字典中所有的项

fromkeys

>>> dict.fromkeys(['apple', 'orange'], 1)    
{'apple': 1, 'orange': 1}

get

>>> d = {}
>>> print(d['name'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'name'

>>> d = {}
>>> print(d.get('name'))
None
>>> print(d.get('name', 'N/A'))
N/A
>>> d['name'] = 'Noah'
>>> print(d.get('name', 'N/A'))
Noah

items / loop

>>> m
{'apple': 1, 'orange': 1}
>>> m.items()
dict_items([('apple', 1), ('orange', 1)])   
>>> for i in m.items():
...     print(i)
... 
('apple', 1)
('orange', 1)

>>> m = {'apple': 1, 'orange': 1}
>>> for k, v in m.items():
...   print('k: {}, v: {}'.format(k, v))
...
k: apple, v: 1
k: orange, v: 1

keys

person = {"age":30,"gender":"male","height":183,"weight":140}
person.keys()

values

person = {"age":30,"gender":"male","height":183,"weight":140}
person.values()

pop

>>> d = {'x':1, 'y':2, 'z':3}
>>> d.pop('y')
2
>>> d
{'x': 1, 'z': 3}    

update

>>> x = {1:'a', 2:'b'}
>>> x
{1: 'a', 2: 'b'}
>>> y = {1:'b', 3:'c'}
>>> x.update(y)
>>> x
{1: 'b', 2: 'b', 3: 'c'}

>>> person = {"name": "noah", "age": 30}
>>> person.update({"age": 32})
>>> person
{'name': 'noah', 'age': 32} 

sorted

d = {1:0,2:3,3:2,5:1}
sorted(d.items(), key=lambda x: x[0]) # sorted by key
sorted(d.items(), key=lambda x: x[1]) # sorted by value
sorted(d.items(), key=lambda x: x[1], reverse=True) # sorted by value desc

Python

这篇文章: 有用 无用
创建 2018-08-05 07:48:13 / 更新 2019-03-26 22:38:51

使用Perl建立一个文件服务器

当你需要从Linux上下载一些文件,而你又使用的是Windows,那么建立一个文件服务器会很方便

首先你需要安装Plack模块

然后创建app.psgi文件并写入:

#!/usr/bin/perl
use strict;
use warnings;
use Plack::App::Directory;

my $app = Plack::App::Directory->new({ 
                root => "/path/to/htdocs" 
            })->to_app;

最后运行:

> plackup
> Accepting connections at http://0:5000/

注意:

plackup -p, --port 可以改变服务的端口,默认端口为5000

确保服务端口没有被禁用

参考:

Plack::App::Directory

plackup

Plack


Perl

这篇文章: 有用 无用
创建 2018-07-11 20:06:47 / 更新 2018-07-11 20:14:11

Python 列表和元组

列表和元组的主要区别是,列表可以修改,元组不能

如何定义一个列表:

pen_holder = ['pen', 'refill', 'bookmarks']

索引:

pen_holder[0] # pen
pen_holder[-1] # bookmarks

分片(前包含,后不包含):

pen_holder[0:2] # ['pen', 'refill']
pen_holder[-3:-1] # ['pen', 'refill']
pen_holder[-2:] # ['refill', 'bookmarks']
pen_holder[1:] # ['refill', 'bookmarks']
pen_holder[:] # ['pen', 'refill', 'bookmarks'] 复制一个列表,不会指向原列表

分片和步长(默认步长为1):

pen_holder[::2] # ['pen', 'bookmarks']
pen_holder[::-2] # ['bookmarks', 'pen'] # 步长为负,从右向左
pen_holder[::-1] # ['bookmarks', 'refill', 'pen'] # 数组反序

序列相加:

[1,2,3] + [4,5,6] # [1,2,3,4,5,6]

乘法:

[8] * 8 # [8,8,8,8,8,8,8,8]

初始化一个长度为10的列表:

seq = [None] * 10 # None是Python的一个内建值,表示“什么也没有”

成员资格:

'pen' in pen_holder # True
'spoon' in pen_holder # False

database = [
    ['albert', '1234'],
    ['noah', '2342'],
    ['json', '4565']
]                

['alert', '1234'] in database # True
['alert', '3423'] in database # False

长度,最小值,最大值:

len(pen_holder) # 3
min(pen_holder) # 'bookmarks'        
max(pen_holder) # 'refill'
min(1,2,3) # 1
max(1,2,3) # 3

list函数:

list('Big') # ['B', 'i', 'g']

元素赋值:

不能为一个位置不存在的元素进行赋值,如果列表长度为2,那么不能为索引为2的元素进行赋值。如果需要给索引为2的元素赋值,需要创建一个长度至少为3的列表。

pen_holder[0] = 'bottle opener'

删除元素:

del open_holder[0]

分片赋值:

可以使用与原长不等长的序列替换

name = list('Noah')
name[1:] = 'ikky' # ['N', 'i', 'k', 'k', 'y']

name = list('Big')
name[3:] = 'ger' # ['B', 'i', 'g', 'g', 'e', 'r'] # 在结尾插入
''.join(name) # Bigger  

name = list('word')
name[:0] = 's' # ['s', 'w', 'o', 'r', 'd']  

列表的方法

append

pen_holder.append('card')

pop

pen_holder.pop() # 'card'   

extend

pen_holder.extend(['key', 'charger'])

count

x = [[1,2], 1, 2, 1, [1,2,3]]    
x.count(1) # 2
x.count([1,2]) # 1

index

x = ['We', 'are', 'the', 'world']
x.index('are') # 1
x.index('work') # 异常

insert

x = [1,3,4,5]
x.insert(0, 0)
x.insert(2, 2) # [0, 1, 2, 3, 4, 5]

remove

移除列表中某个值的第一个匹配项

x = ['I', 'am', 'a', 'Chinese']
x.remove('a') 
x.remove('an') # 异常

reverse

将列表的元素反向存放

x = [1,2,3]
x.reverse()  

sort

x = [4,2,1,3,5]
x.sort # [1,2,3,4,5] 改变原列表

y = sorted(x) # 不会改变原列表            

Python

这篇文章: 有用 无用
创建 2018-06-20 17:13:01 / 更新 2018-06-20 17:13:01

Python中使用RSA加密解密

首先安装rsa包

pip install rsa

需要使用openssl生成private key

openssl genrsa -out key.pem 1024

再生成public key

openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem

然后就可以使用代码测试了

#/usr/bin/python
# -*- coding: utf-8 -*-

import rsa
from os.path import expanduser

home = expanduser("~")

with open(home+'/.ssh/key.pem', mode='rb') as privfile:
    keydata = privfile.read()
privkey = rsa.PrivateKey.load_pkcs1(keydata)

with open(home+'/.ssh/pubkey.pem', mode='rb') as pubfile:
    keydata = pubfile.read()
pubkey = rsa.PublicKey.load_pkcs1(keydata)

message = u'我是中国人'.encode('utf-8')
crypto = rsa.encrypt(message, pubkey)

icrypto = rsa.transform.bytes2int(crypto)
print(icrypto)
crypto = rsa.transform.int2bytes(icrypto)

message = rsa.decrypt(crypto, privkey)
print(message.decode('utf-8'))    

参考:

openssl generate public rsa key

rsa

RSA encryption and decryption

RSA int2bytes bytes2int


Python

这篇文章: 有用 无用
创建 2018-06-16 20:01:58 / 更新 2018-07-05 01:34:49