Python 循环与迭代:深入解析
1. 命令行工具与模拟
在 Python 中, os.popen
和 os.system
等工具能让我们利用计算机上的所有命令行程序。同时,我们也可以用进程内代码编写模拟器。例如,模拟 Unix 的 awk
工具从文本文件中提取列非常简单,还能将其封装成可复用的函数:
# awk 模拟:从以空格分隔的文件中提取第 7 列
for val in [line.split()[6] for line in open('input.txt')]:
print(val)
# 同样的功能,但代码更明确,保留结果
col7 = []
for line in open('input.txt'):
cols = line.split()
col7.append(cols[6])
for item in col7:
print(item)
# 同样的功能,但封装成可复用的函数
def awker(file, col):
return [line.rstrip().split()[col - 1] for line in open(file)]
print(awker('input.txt', 7)) # 字符串列表
print(','.join(awker('input.txt', 7))) # 用逗号分隔
2. 网络数据访问
Python 还能提供对各种数据的类文件访问,包括通过 URL 访问网站及其页面返回的文本: </