常用文件操作函数
- open():打开文件
- read():读取文件的内容,可以把内容赋值给一个变量。
- close():关闭文件,就像文件编辑器里面的保存
- readline():读取文件中的一行
- truncate():清空文件中的内容
- write(‘stuff’):向文件中写数据’stuff’
代码:
from sys import argv
script, filename = argv
print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filename, 'w')
print "Truncating the file. Goodbye!"
target.truncate()
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."
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "And finally, we close it."
target.close()
得到的结果图:
以及文件data.in中的数据:
我们可以看到在读取文件的时候在后面加了一个字符’w’。这个符号表示用怎么得方式读取文件。一共有三种方式读取文件(r,w,a):
- r方式:就是只读方式,可以在后添加+,b等r+表示可读写,rb表示以二进制读取;
- w方式:就是只写方式,可以在后添加+,b等w+表示可读写,wb表示以二进制读取;
- a方式:就是从在文章末尾写的方式,可以在后田间+,b,意思同上。