Python學習16:讀寫檔案

來源:互聯網
上載者:User

標籤:rom   讀寫   put   test   關閉   使用   檔案   print   and   

一個簡單的文字編輯器

# -*- coding: utf-8 -*-from sys import argv  # 從sys模組匯入argv函數,#「argv」是「argument variable」參數變數的簡寫形式。一般在命令列調用的時候由系統傳遞給程式。# 一般在命令列調用的時候由系統傳遞給程式。script, filename = argv # 利用argv函數,把 argv 中的東西解包,將所有的參數依次賦予左邊的變數名print "We‘re going to erase %r." % filename # 列印檔案名參數print "If you don‘t want that, hit CTRL-C (^C)." # 提示輸入CTRL+C就退出程式print "If you do want that, hit RETURN." printprint "Here is the original file: "printtxt = open(filename) # 使用open函數開啟檔案,並把內容存到txt變數中print txt.read() # 讀取txt的內容並列印出來,這一塊是為了讀取未清除檔案內容並寫入其他內容之前的內容raw_input("?")print "Opening the file..."target = open(filename, ‘w‘) # 以寫入模式開啟檔案print "Truncating the file. Goodbye!"target.truncate() # 用truncate函數清除檔案內容print "Now I‘m going to ask you for three lines."print#line1 = raw_input("Line 1: ") # 寫入三行內容,儲存到line1,line2和line3的變數中txt1 = open(filename, ‘w‘)txt1.write (‘This is a test.\nReally, it is.‘)txt1.close()printprint "I‘m going to write these to the file."printtarget.write(line2) # 使用write函數把line1變數中target.write("\n") # 使用write函數寫入一個分行符號target.write(line2) #使用write函數把line2變數中target.write("\n") # 使用write函數寫入一個分行符號target.write(line3) #使用write函數把line3變數中target.write("\n") # 使用write函數寫入一個分行符號printprint "And finally, we close it."target.close() # 關閉檔案filename1 = raw_input("input a filename: ")filename1_open = open(filename1) # 開啟檔案print "Here is the new file content: "printprint filename1_open.read() # 讀取新的檔案內容print "close opened file..."filename1_open.close() # 關閉檔案

Python學習16:讀寫檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.