Python學習16:讀寫文件

一個簡單的文本編輯器

# -*- 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." 
print
print "Here is the original file: "
print
txt = 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()

print
print "I'm going to write these to the file."
print
target.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函數寫入一個換行符
print
print "And finally, we close it."
target.close() # 關閉文件

filename1 = raw_input("input a filename: ")
filename1_open = open(filename1) # 打開文件

print "Here is the new file content: "
print

print filename1_open.read() # 讀取新的文件內容
print "close opened file..."
filename1_open.close() # 關閉文件
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章