Python 输入和输出,Python输入输出,一、在控制台上输入、
Python 输入和输出,Python输入输出,一、在控制台上输入、
一、在控制台上输入、输出
inputvalue1 = input("please input:")print(inputvalue1)rawinputvalue1 = raw_input("the value of rawinputvalue1:")print(rawinputvalue1)
结果:
please input:‘hello‘hellothe value of rawinputvalue1:hellohello
input严格遵守python的语法,如输入字符串,则必须加上单引号,否则会报错;
而raw_input不会有这些限制;
二、文件
1、open函数打开文件
语法如下:
open(name[,mode[,buffering]]),文件名为必填参数,模式和缓冲参数是可选的。
最简单的示例如下:
open(r‘c:\text\file.txt‘)
(1)模式mode
文件的模式作用是控制用户读、写文件等权限;默认权限是读模式,即参数mode没有赋值时,用户只能读文件。
‘+’参数可以用到其它任何模式中,指明读和写都是允许的。
(2)缓冲
如果参数是0(或者是false),I/O就是无缓冲的(所有的读写操作都直接针对硬盘);如果是1(或者是true),I/O就是有缓冲的(以为这Python使用内存来代替硬盘,让程序更快,只有使用flush或者close时才会更新硬盘上的数据)。大于1的数字代表缓冲区的大小(单位是字节),-1(或者是任何负数)代表使用默认的缓冲区大小。
2、读、写文件
(1)读写字符
write和read方法分别表示写、读文件。
write方法会追加字符串到文件中已存在部分的后面。
read方法会按字符顺序读取文件。
f=open(r‘D:\Python.txt‘,‘w‘)f.write("hello")f.write("world")f.close()f=open(r‘D:\Python.txt‘,‘r‘)print(f.read(1)) #hprint(f.read(3)) #ell
(2)读写行
writelines和readlines\readline可以按行写入或读取文件
f=open(r‘D:\Python.txt‘,‘w‘)f.writelines("hello,susan\n")f.writelines("hello,world\n")f.writelines("hello,python\n")f.close()f=open(r‘D:\Python.txt‘,‘r‘)print(f.readline()) #hello,susan#没有f.writeline()方法,因为可以使用writeprint(f.readlines()) #[‘hello,world\n‘, ‘hello,python\n‘]
(3)文件对象可迭代
文件对象是可迭代的,这意味着可以直接在for循环中使用它们。
f=open(r‘D:\Python.txt‘)for line in f: print(line) #每次读取一行内容
3、关闭文件
如果想确保文件被关闭了,那么应该使用try/finally语句,并且在finally子句中调用close方法
也可以使用with语句;
with语句可以打开文件并且将其赋值到变量上,之后就可以将数据执行其他操作。文件在语句结束后会被自动关闭,即使是由于异常引起的结束也是如此。
#open file heretry: #write data to filefinally: file.close()with open(r‘D:\Python.txt‘,‘r‘) as f: print(f.readline()) #hello,world
本文内容摘自《Python基础教程》一书
Python 输入和输出
相关内容
- python2升级python3,,一 python2升
- 彻底弄清python的切片,,lis = rang
- python -使用del语句删除对象引用,,使用del语句删除一
- 0039-如何使用Python Impyla客户端连接Hive和Impala,0039-imp
- python 调用js代码,python调用js,Python2 安
- openstack开发环境与代码测试,openstack开发代码,一、op
- ubuntu python opencv3 cv2.cv2 has no attribute 'face'
- [leetcode]Validate Binary Search Tree @ Python,,原题地址:http
- python重置ie代理 用于ss使用后的恢复,pythonss,每次用完
- Hunt the wumpus 《Python代码》,, 1 from ra
评论关闭