笨方法學python,Lesson15,16,17

Exercise 15 python

代碼函數

from sys import argv 

script, filename = argv 

txt = open(filename)

print "Here is your file %r:" % filename 
print txt.read()

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

txt_again = open(file_again)

print txt_again.read()

輸出code

Notes:對象

①查看python文檔,python提示打開文件的首選方法是open(name[,mode[,buffering]])函數
three

②文件對象.read()方法讀取文件內容,有一個可選參數選擇讀取的長度,語法爲file.read([size])ip

③在python的交互模式中打開文件,需輸入文件的完整目錄
ci

>>> txt = open("E:\\code\\LPTHW\\ex15_sample.txt")
>>> print txt.read()
One
Two
Three

④文件對象.close()用於保存並關閉文件,在對文件操做完成後關閉文件文檔

Exercise 16字符串

代碼
get

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."

raw_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 = raw_input("Line 1: ")
line2 = raw_input("Line 2: ")
line3 = raw_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")

print "And finally, we close it."
target.close()

輸出

Notes:

①文件對象.truncate()方法會清除文件內容

②write()方法把括號中的字符串對象寫入文件中,字符串對象支持格式化及轉義操做

③open()打開模式'w'表示也寫的方式打開,文件不存在會被建立,已存在會在打開時清空內容。不添加打開參數時,open()默認以只讀的方式打開文件

Exercise 17

代碼

from sys import argv
from os.path import exists 

script, from_file, to_file = argv 

print "Copying from %s to %s" % (from_file,to_file)

# we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()

out_file = open(to_file,"w")
out_file.write(indata)

print "Alright, all done."

out_file.close()
in_file.close()

輸出

Notes:

①os.path模塊中的exists()函數用來判斷一個文件是否存在,存在返回True,不然返回False

相關文章
相關標籤/搜索