《笨办法学python》源码 Ex16.py







------------

#-------------------------------------------------------------------------------
# Name:        ex_16.py
# Purpose:     读写文件.
#              close          关闭文件
#              read           读取文件内容.
#              readline       读取一行文本.
#              truncate       清空文件.
#              write(stuff)   将stuff写入文件.
#
# Author:      huanghuan
#
# Created:     14-08-2013
# Copyright:   (c) huanghuan 2013
# Licence:     <your licence>
#-------------------------------------------------------------------------------


from sys import argv

script, file_name = argv
# 文本编辑器.
print "Erase %r." % file_name
print "Yes,hit Return.      No, hit Ctrl-C (^C)."

raw_input("?")

print "Opening the file..."
# 打开文件
target = open(file_name,'w')

print "Truncating the file. Goodbye!"
# 清空文件内容
target.truncate()

print "Input three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print " Write these into the file."
# 依次写入3行文本.
# 写入1行内容.
target.write(line1)
# 写入换行符.
target.write("\n")

target.write(line2)
target.write("\n")

target.write(line3)
target.write("\n")

#-------------------
# 连续写入10行.
i = 0
for i in range(10):
    target.write(line1)
    target.write("\n")
    i+= 1



# 关闭文件.
print "finally,we close it."
target.close()


txt文本内容如下:

-----------------

hello ......
**********
goodbye....
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......
hello ......


你可能感兴趣的:(《笨办法学python》源码 Ex16.py)