码迷,mamicode.com
首页 > 编程语言 > 详细

Python 输入和输出

时间:2019-05-16 19:07:56      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:ring   ase   style   put   data   value   lse   参数   HERE   

一、在控制台上输入、输出

inputvalue1 = input("please input:")
print(inputvalue1)
rawinputvalue1 = raw_input("the value of rawinputvalue1:")
print(rawinputvalue1)

结果:

please input:hello
hello
the value of rawinputvalue1:hello
hello

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(rD:\Python.txt,w)
f.write("hello")
f.write("world")
f.close()

f=open(rD:\Python.txt,r)
print(f.read(1)) #h
print(f.read(3)) #ell

(2)读写行

writelines和readlines\readline可以按行写入或读取文件

f=open(rD:\Python.txt,w)
f.writelines("hello,susan\n")
f.writelines("hello,world\n")
f.writelines("hello,python\n")
f.close()

f=open(rD:\Python.txt,r)
print(f.readline()) #hello,susan
#没有f.writeline()方法,因为可以使用write
print(f.readlines()) #[‘hello,world\n‘, ‘hello,python\n‘]

(3)文件对象可迭代

文件对象是可迭代的,这意味着可以直接在for循环中使用它们。

f=open(rD:\Python.txt)
for line in f:
    print(line)  #每次读取一行内容

3、关闭文件

如果想确保文件被关闭了,那么应该使用try/finally语句,并且在finally子句中调用close方法

也可以使用with语句;

with语句可以打开文件并且将其赋值到变量上,之后就可以将数据执行其他操作。文件在语句结束后会被自动关闭,即使是由于异常引起的结束也是如此。

#open file here
try:
    #write data to file
finally:
    file.close()


with open(rD:\Python.txt,r) as f:
    print(f.readline()) #hello,world

 

本文内容摘自《Python基础教程》一书

 

Python 输入和输出

标签:ring   ase   style   put   data   value   lse   参数   HERE   

原文地址:https://www.cnblogs.com/susan-su/p/10871638.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!