Published 8月 16, 2018 by with 0 comment

習題17 - 更多文件操作




先用Notepad++打上下列的文字,
另存為ex17_sample_1.txt
111AAA
222BBB
333CCC

再用Notepad++打下列的程式碼,
另存為ex17.py. 我附上中文注釋方便好讀.
# -*- coding: utf-8 -*-
#從sys導入argv模組
from sys import argv
#從os.path導入exists模組, 該模組能測試文件是否存在(True/False)
from os.path import exists

#加入三個參數到argv(PY程式, 被複制的檔案, 要複製到文件名)
script, from_file, to_file = argv

#印出從被複制的檔案名到要複製到的文件名
print (f"Copying from {from_file} to {to_file}")

# we could do these two on one line, how?
#打開(被複制的檔案), 讀取內容到indata
in_file = open(from_file)
indata = in_file.read()

#計算該(被複制的檔案)的檔案長度(len)
print (f"The input file is {len(indata)} bytes long")

#用exists測試(要複製到文件名)是否存在並打印出來
print (f"Does the output file exist? {exists(to_file)}")
print ("Ready, hit RETURN to continue, CTRL-C to abort")
input ()

#打開(要複製到文件名)並寫入indata(被複制的檔案)的內容到out_file(要複製到文件名).
out_file = open (to_file, "w")
out_file.write(indata)

print ("Alrightm all done.")

#關閉兩個已打開的文件
out_file.close()
in_file.close()

然後用Windows的cmd, 執行python打開它. (並在後面加了2個參數: ex17_sample_1.txt ex17_sample_2.txt)
C:\Users\Peter\Desktop\Python\LP3THW>python ./ex17.py ex17_sample_1.txt ex17_sample_2.txt
Copying from ex17_sample_1.txt to ex17_sample_2.txt
The input file is 20 bytes long
Does the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort

Alrightm all done.

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

完成

這段程式碼主要是讀取ex17_sample_1.txt的內容,
測量其檔案大小,
檢查ex17_sample_2.txt是否存在,
然後將ex17_sample_1.txt的內容copy到ex17_sample_2.txt.

結果,
檢查一下兩個檔案,
被複制的檔案: ex17_sample_1.txt
要複製到文件名: ex17_sample_2.txt
應該要完全一樣.
C:\Users\Peter\Desktop\Python\LP3THW>type ex17_sample_1.txt
111AAA
222BBB
333CCC
C:\Users\Peter\Desktop\Python\LP3THW>
C:\Users\Peter\Desktop\Python\LP3THW>type ex17_sample_2.txt
111AAA
222BBB
333CCC
C:\Users\Peter\Desktop\Python\LP3THW>



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

0 comments:

張貼留言