python语法(5)

读写文件

#读取文件,在脚本的同级目录下有一个可读的txt文件
#coding=utf-8
from sys import argv
script,filename=argv 
txt=open(filename) #open打开文件
print ("Here's your file %r:"%filename)
print (txt.read())#测试是否关闭了
print ("Type the filename again:")
file_again=input(">")
txt_again=open(file_again)
print (txt_again.read())#read输出文件

'''
#读写文件
#close关闭文件,read读取文件内容,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")
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=input("line 1:")
line2=input("line 2:")
line3=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")
#也可以一次写入 
#target.write(line1+"\n"+line2+"\n"+line3+"\n")
print ("And finally,we close it")
target.close()
'''

  

posted on 2017-12-17 15:48  never1211  阅读(49)  评论(0编辑  收藏  举报

导航