笨方法學習Python-習題16: 讀寫文件

# coding=utf-8

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...")
'''
打開文件 “w”是特殊字符串,用來表示訪問模式
“w”是寫入,還有“r”表示讀取(read),“a”表示追加(append)
'''
target = open(filename,'w')

print("Truncating the file. Goodbye!")
# 清空文件內容 open(filename,'w')中,表示可以寫入文件,所以此處註釋
#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("%s\n%s\n%s\n"%(line1,line2,line3))
'''
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()

"""
文件的相關方法/函數:
• close – 關閉文件。跟你編輯器的 文件->保存.. 一個意思。
• read – 讀取文件內容。你可以把結果賦給一個變量。
• readline – 讀取文本文件中的一行。
• truncate – 清空文件,請小心使用該命令。
• write(stuff) – 將 stuff 寫入文件。 
"""

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章