您的位置:首页 > 编程语言 > Python开发

python入门——笔记1

2017-03-24 22:03 218 查看
通过阅读《”笨方法“学python(第三版)》,书写的很细很简单,适合没有编程基础的人自学python。

因为我用的python3,书中的介绍是用的python2,所以有些地方有些偏差。

使用Notepad++以及cmd命令行用做python代码编写及运行。

一、输出带有中文字符时,需要将Notepad++的编码方式改成utf-8,python3默认的编码方式应该就是utf-8,即使没有在程序开头注释使用utf-8,或者直接在cmd里面输入python之后输出中文,都不会出错。对于python2需要把notepad++编码方式改为ansi,然后程序第一行加入#coding:utf-8,否则python内部运行正确,但是cmd使用python file.py运行乱码。

二、python3对于除法输出都是浮点数的形式。

三、%r输出的是数据的原始格式,对于数值类型,输出与%s、%d一样,对于字符串类型,输出两头多了单引号。

四、python3没有raw_input(),只有input(),存储格式是字符串形式。可以用int(input())将输入转换为int格式,用float(input())转换为浮点数。

五、python没有double只有float。

六、用bool(x)将x转换为bool类型时,x为数值类型的0,字符型为空时为false。

七、文件操作

open(filename , mode = 'r', buffering = -1,.....)

'r'只读;'w'写,如果文件存在,则清除;'x'新建文件并写入;'a'文件尾写入;‘b’二进制格式;‘+’读写模式;‘t’文本文件格式,默认。

对于python3,windows下面的r+和a+都是从文件尾写入,w+将文件删除之后写入,注意write后read指针指向文件尾,需要seek(0)使指针指向文件头。

对于python2,由于底层使用c实现,所以对于文件读写操作要非常小心。首先,在写入是,在write操作之后要加上flush或者seek(0,1),否则写入内容会有很多乱码,个人猜测应该是python在写入之后不能自行定位文件尾。另外,在write之后read是从当前文件指针处开始读取,所以如果当前写入内容是新增在文件尾的,那么read内容为空。在read操作之后,进行write操作时,往往会报错,IOError,errno 0,是因为在read操作之后读写交替过程中必须要有fflush,
fseek, fsetpos, rewind这类操作,python不知道当前文件位置在哪,所以需要加上seek进行文件指针定位。

seek(offset,whence),whence默认为0,就是文件头,1为当前位置,2为文件尾。

下面代码为书中习题16的衍生代码。

#coding:utf-8
#author:lx

from sys import argv

script, filename = argv

target = open(filename, 'w+')

line1 = raw_input("line 1:")
line2 = raw_input("line 2:")
line3 = raw_input("line 3:")

print ("I'm going to write these to the file.")
target.write(line1+"\n"+line2+"\n"+line3+"\n")
target.seek(0,1)
#target.flush()
target.close()
test = open(filename, 'r+')
print ("origina:\n",)
print (test.read())
print ("Now I'm going to ask you for three lines.")
line1 = raw_input("line 1:")
line2 = raw_input("line 2:")
line3 = raw_input("line 3:")

print ("I'm going to write these to the file.")
test.seek(0,2)
test.write(line1)
test.write("\n")
test.write(line2)
test.write("\n")
test.write(line3)
test.write("\n")
#test.flush()
test.seek(0,0)
print (test.read())
print ("And finnally, we close it.")
test.close()
运行opne(file).read()时不需要调用close()了,因为read()一旦运行,文件会被python关掉。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: