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

python学习笔记17:文件操作

2014-10-18 09:10 519 查看
1. 文本的读入和写出

文件的绝对路径和相对路径:绝对路径指从根目录开始的路径;相对路径指从当前目录开始的路径。

文本文件和二进制文件:尽管不准确,可以将文本文件看成是字符序列,而将二进制文件看成是二进制序列;字符序列可以通过Ascii, unicode等解码,二进制序列可直接解码。当然在计算机中是不区分这些文件,都是以二进制存储的。

1)open

fileVarible = open(filename, mode)

关于mode,有以下几种方式:

"r" :以读方式打开文件;

"w":以写方式打开文件,如果存在该文件,则原始文件内容被破坏;如果该文件不存在,则创建该文件;

"a":以将数据append到文件的末尾方式打开文件;

"rb":以读方式打开二进制文件;

"wb":以写方式打开二进制文件;

2)读写函数

write(s:str):写数据到文件中;

def test1():
# write
outfile = open("Presidents.txt","w")
outfile.write("Bill Clinton\n")
outfile.write("Geogre Bush\n")

outfile.close()


read([number.int]):读取指定数目字符,如果参数不指定,则默认读取整个文件;

readline():返回str,读取下一行数据;

readlines():返回一个list,读取接下来的所有行;

def test2():
# read demo
infile = open("Presidents.txt","r")
print ("1. using read")
print (infile.read())
infile.close()

infile = open("Presidents.txt","r")
print ("2. using read(number)")
s1 = infile.read(4)
print (s1)
s2 = infile.read(10)
print (s2)
infile.close()

infile = open("Presidents.txt","r")
print ("3. using readline()")
line1 = infile.readline()
line2 = infile.readline()
print (repr(line1))
print (repr(line2))
infile.close()

infile = open("Presidents.txt","r")
print ("4. using readlines()")
print (infile.readlines())
infile.close()


close():关闭文件;

另外补充一个判断路径是否存在的函数isfile(),在os.path包中;

2. 异常处理

在上面的文件读取中,如果读取某个文件,但它不存在,则系统会报出IOError错误,这个时候可以用:

try:

<body>

except <ExceptionType>:

<handler>

做处理,如果运行时出现了ExceptionType错误,则try下面的语句都不会执行。更广泛的可以有多个handler,如:

try:

<body>

except <ExceptionType1>:

<handler1>

except <ExceptionType2>:

<handler2>

...

except <ExceptionTypeN>:

<handlerN>

else:

<process else>

finally:

<process_finally>

举个例子:

def test3():
try:
number1,number2 = eval(input("请输入两个数,以逗号隔开:"))
result = number1/number2
print ("Result is", result)
except ZeroDivisionError:
print ("Division by zero!")
except SyntaxError:
print ("A comma may be missing in the input!")
except:
print ("Something wrong in the input!")
else:
print ("No exceptions!")
finally:
print ("The finally clause is excuted.")


另外,还可以在函数体中抛出异常,如raise RuntimeError("wrong arg")。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: