ex15~ex16文件操作

進(jìn)入文件操作部分,這里涉及文件操作的一些方法,先羅列在下面:

  • open--打開文件
    • r只讀,r+讀寫
    • w新建,w+讀寫,寫入(會覆蓋原有文件)
    • a追加,a+以讀寫模式打開,若文件不存在自行創(chuàng)建
    • b二進(jìn)制文件
  • close--關(guān)閉文件,跟你編輯器的文件 文件->保存 .. 一個(gè)意思
  • read--讀取文本內(nèi)容,可以賦給一個(gè)變量
  • readline --讀取文本文件中的一行
  • truncate-- 清空文件,謹(jǐn)慎使用
  • write(“stuff”)--將stuff寫入文件

ex15

#coding=utf-8
from sys import argv
script, filename = argv #參數(shù)解包到兩個(gè)變量script, filename

txt = open(filename) #打開filename文件,文件對象

print "Here's your file %r:" % filename
print txt.read() #讀取txt內(nèi)容
txt.close()

print "Type the filename again:"
file_again =raw_input("> ")

txt_again = open(file_again) #再次打開文件

print txt_again.read() #打印文件內(nèi)容
txt_again.close()

ex16

#coding=utf-8
from sys import argv

script, filename = argv #filename文件本來沒有
                        #命令行直接輸入文件名后自動創(chuàng)建新空文檔

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C."
print "If you do want that, hit RETURN."

raw_input("?")

print "Opening the file..."
target = open(filename,'w') #以寫試打開文件

print "Truncating the file. Goodbye!"
target.truncate() #刪除文件原有內(nèi)容 

print "Now I'm going to ask you for three lines."

line1 = raw_input("line1: ")
line2 = raw_input("line2: ")
line3 = raw_input("line3: ")

print "I'm going to write these to the file."

target.write(line1) #寫入第一行內(nèi)容
target.write("\n") #換行
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")

print "And finally, we close it."
target.close() #操作完成后關(guān)閉文件
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容