使用os.path 模块中的函数来完成多数操作
使用os.path 来进行文件测试是很简单的。在写这些脚本时,可能唯一需要注意的就是你需要考虑文件权限的问题,特别是在获取元数据时候
>>> import os
>>> path = '/Users/beazley/Data/data.csv'
>>> # Get the last component of the path
>>> os.path.basename(path)
'data.csv'
>>> # Get the directory name
>>> os.path.dirname(path)
'/Users/beazley/Data'
>>> # Join path components together
>>> os.path.join('tmp', 'data', os.path.basename(path))
'tmp/data/data.csv'
>>> # Expand the user's home directory
>>> path = '~/Data/data.csv'
>>> os.path.expanduser(path)
'/Users/beazley/Data/data.csv'
>>> # Split the file extension
>>> os.path.splitext(path)
('~/Data/data', '.csv')
>>> os.path.exists('/etc/passwd')
True
>>> # Is a regular file
>>> os.path.isfile('/etc/passwd')
True
>>> # Is a directory
>>> os.path.isdir('/etc/passwd')
False
>>> # Is a symbolic link
>>> os.path.islink('/usr/local/bin/python3')
True
>>> # Get the file linked to
>>> os.path.realpath('/usr/local/bin/python3')
'/usr/local/bin/python3.3'
>>> os.path.getsize('/etc/passwd')
3669
>>> os.path.getmtime('/etc/passwd')
1272478234.0
>>> import time
>>> time.ctime(os.path.getmtime('/etc/passwd'))
'Wed Apr 28 13:10:34 2010'
使用os.listdir() 函数来获取某个目录中的文件列表
与串行端口的数据通信最好的选择是使用pySerial 包。这个包的使用非常简单,先安装pySerial。
import serial
ser = serial.Serial('/dev/tty.usbmodem641', # Device name varies
baudrate=9600,
bytesize=8,
parity='N',
stopbits=1)
ser.write(b'G1 X50 Y50\r\n')
resp = ser.readline()
序列化Python 对象将一个Python 对象序列化为一个字节流,以便将它保存到一个文件、存储到数据库或者通过网络传输它。对于序列化最普遍的做法就是使用pickle 模块。
import pickle
data = ... # Some Python object
f = open('somefile', 'wb')
pickle.dump(data, f)