Published 8月 14, 2018 by with 0 comment

習題15 - 讀取文件




先用Notepad++打下列的文字,
另存為ex15_sample.txt.
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

再用Notepad++打下列的程式碼,
另存為ex15.py.
from sys import argv

script, filename = argv

txt = open (filename)

print (f"Here's your file {filename}:")
print (txt.read())

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

txt_again = open(file_again)
print (txt_again.read())

然後用Windows的cmd, 執行python打開它. (並在後面加了1個參數: ex15_sample.txt)
C:\Windows\System32>cd C:\Users\Peter\Desktop\Python\LP3THW

C:\Users\Peter\Desktop\Python\LP3THW>python .\ex15.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
> ex15_sample.txt
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.

C:\Users\Peter\Desktop\Python\LP3THW>

完成

我們來修改一下程式碼.
Line 5, 使用UTF-8編碼, 如此一來便可顯示中文等非英文字體.
Line 9 & 18, 關閉文件, 順序很重要 open > read > close.
Line 12, 使用格式化, 顯示出script名稱.
from sys import argv

script, filename = argv

txt = open (filename, encoding = "UTF-8")

print (f"Here's your file {filename}:")
print (txt.read())
txt.close()

print ("Type the filename again:")
file_again = input (f"{script}> ")

txt_again = open(file_again)

print (txt_again.read())

txt_again.close()

結果,
Line 7, 我輸入同一個檔案夾中其他的檔案名稱, 也是能正確顯示.
C:\Users\Peter\Desktop\Python\LP3THW>python ex15.py ex15_sample.txt
Here's your file ex15_sample.txt:
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Type the filename again:
ex15.py> ex1.py
print ("Hello World!")
print ("Hello Again")
print ("I like typing this.")
print ("This is fun.")
print ('Yay! Printing.')
print ("I'd much rather you 'not'.")
print ('I "said" do not touch this.')

C:\Users\Peter\Desktop\Python\LP3THW>



最初發表  /  最後更新: 2018.08.14  /  2018.08.14

0 comments:

張貼留言