#! /usr/bin/python
'''
在系统中键入文件名并创建空文件,并将字符串写入文件中。
利用%s将字符串传递,并在write函数中使用%s字符串传递,
并将\n使用在其中,write函数中还调用变量
'''
file_name = raw_input("pls input your file name: ") #键入文件名
print "we're going to erase %r. " % file_name
print "if you want to quit, hit CTRL-C !"
print "if you want to that, hit Enter !"
raw_input("waiting for you...")
print "Opening the file..."
writefile = open(file_name,'w') # W是写入,即可创建文件
writefile.truncate() # truncate官方称为字符截断,试验下来其只针对文件 append 模式有效,个人理解为保留多少个字符以后开始替换修改。
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 "Now i will write these to the file!!"
writefile.write(line1+"\n") #调用变量,写入文件
writefile.write(line2)
writefile.write("\n")
writefile.write("%s\n\n%s" % (line3,line1))
writefile.write("\n\n\n\n%s\t%s" % (line3,line2))
writefile.write(line1+"\n"+line2+"\n"+line3+'\n'+'yes'+"\n") #调优后的,采用字符串拼接的方式
writefile.write("%s\t%s\t%s\n" % (line1,line2,line3)) #与上一行效果一样,写法不通,采用字符串传递的方式
print "Finally,we are okay.will close it!"
writefile.close()
阅读(3967) | 评论(0) | 转发(0) |