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

重新梳理Python基础(4)

2013-03-16 12:10 441 查看
1. 文件写操作

文件写操作,需要在打开文件的时候添加参数,如

open("filename", "w")

以下是对文件操作的函数小结

close -- Closes the file. Like File->Save.. in your editor.
read -- Reads the contents of the file, you can assign the result to a variable.
readline -- Reads just one line of a text file.
truncate -- Empties the file, watch out if you care about the file.需要open的时候添加w参数
write(stuff) -- Writes stuff to the file.


参考代码

View Code

from sys import argv
from os.path import exists

script, input_file = argv

print "Is %r exsit?" % input_file
exists(input_file)
indata = """I have a book.
You have two.
He has three.
"""
open(input_file, "w").write(indata)

def print_all(f):
print f.read()

def rewind(f):
f.seek(0)

def print_a_line(line_count, f):
print str(line_count) + ": ", f.readline()

current_file = open(input_file)

print "First let's print the whole file:\n"

print_all(current_file)

print "Now let's rewind, kind of like a tap."

rewind(current_file)

print "Let's print three lines"

current_line = 1
print_a_line(current_line, current_file)

# current_line = current_line + 1
current_line += 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: