Python初学教程:读取文件,,Python 读取文件#
Python初学教程:读取文件,,Python 读取文件#
Python 读取文件
#!/usr/bin/python# 打印命令行指定的文件import sysfor fn in sys.argv[1:]: try: fin = open(fn, 'r') except: (type, detail) = sys.exc_info()[:2] print "\n*** %s: %s: %s ***" % (fn, type, detail) continue print "\n*** Contents of", fn, "***" # 逐行的打印文件内容 lno = 1 while 1: line = fin.readline() if not line: break; print '%3d: %-s' % (lno, line[:-1]) lno = lno + 1 fin.close()print
上述程序简单的读取命令行传入的文件名,并读取文件的内容,然后打印到控制台。
sys.argv
表示命令行参数,argv的第一个元素是正在执行python脚本的文件名,其余元素是用户输入的命令行参数
sys.exc_info()
返回当前异常的信息,该方法返回值的第一个元素是异常的名字,第二个是详细信息,第三个是异常的堆栈信息
相关内容
- Python 操作 Sqlite3教程,pythonsqlite3,Python编程语言从出
- Python生成RSS,pythonrss,心血来潮要搞下pytho
- Python解析RSS,pythonrss,首先需要安装RSS解析的
- python webpy purge nginx fastcgi cache 代码实现,webpynginx,前几
- Python初学教程:Python使用os.path处理文件路径,pythonos
- Python验证Url地址的正则表达式,python正则表达式,Pytho
- Python连接mysql OperationalError: (1366, "Incorrect string
- Python使用easy_install升级包,pythoneasy_install,easy_install
- Python实现java或者.net的getHashCode()函数,pythongethashcode,
- Python正则表达式入门,python正则表达式,一. 编译正则表
评论关闭