一、python的标准输入和输出
[[email protected] wc]# vim stdin.py #!/usr/bin/python #encoding:utf-8 import sys fd = sys.stdin #等待键盘输入 data = fd.read() #data是记录键盘的输入 sys.stdout.write(data+"\n") #标准的键盘输出,\n是添加换行 [[email protected] wc]# python stdin.py hello,world #按Ctrl+D退出标准的键盘输入 hello,world #打印输入的结果
二、文件处理的一些方法
#定义函数,第二个单词大写,定义变量,全小写,中间有下划线,定义类,
[[email protected] wc]# vim lineCount.py #!/usr/bin/env python #coding:utf8 import sys def lineCount(fd): n = 0 for i in fd: n += 1 return n fd = sys.stdin print lineCount(fd) [[email protected] wc]# python lineCount.py sfds safsaf 2 [[email protected] wc]# vim lineCount.py #!/usr/bin/env python #coding:utf8 import sys def lineCount(readlines): n = 0 for i in fd: n += 1 return n fd = sys.stdin print lineCount(fd) [[email protected] wc]# python lineCount.py shfjh 1 [[email protected] wc]# vim readline.py #!/usr/bin/python f = open(‘/etc/hosts‘) while True: data = f.readline() if not data: break print data, f.close() #养成好习惯,open的文件用close关闭 [[email protected] wc]# python readline.py 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 [[email protected] wc]# vim readline.py #!/usr/bin/python with open(‘/etc/hosts‘) as f: while True: data = f.readline() if not data: break print data, #with open 不用close文件,不在with open的范围内,会自动关闭文件。 [[email protected] wc]# python readline.py 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
时间: 2025-01-16 11:15:55