笨方法學python15 17檔案操作

2021-10-04 02:19:33 字數 1879 閱讀 9758

#15

#從模組匯入檔名

from sys import ar**

script,filename = ar**

#先開啟再讀取

txt = open(filename)

print(f"heres your file :")

print(txt.read())

print(txt.read())

#另一種方式匯入,手動輸入檔名

print("type your filename again:")

file_again = input('>來')

txt_again = open(file_again)

print(txt_again.read())

print("hello world")

#text_again.seek(0)

#print(txt_again.read())

#無法用read連續兩次讀取同一資料夾,一種說法是游標會移動到末尾,用seek重新定位解決而在我這裡行不通,看到另一種說法說read完檔案會直接關閉。

#16

from sys import ar**

script,filename = ar**

print(f"we're going to erase .")

print("if you don't want that, hit ctrl-c(^c).")

print("if you do want that ,hit return.")

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=input("line 1:")

line2=input("line 2:")

line3=input("line 3:")

print("i'm going to write these to the file")

target.write(f"""

""")

print("and finally ,we close it")

target.close()

file_again = input('>來讀一讀')

txt_again = open(file_again)

print(txt_again.read())

#17

from sys import ar**

from os.path import exists

script,from_file, to_file= ar**

print(f"copying from to ")

#we could do these two on one line,how?

indata=open(from_file).read()

print(f"the input file is bytes long")

print(f"does the output file exists?")

input("ready, hit return to continue,ctrl_c to abort")

out_file = open(to_file,'w')

out_file.write(indata)

print("finish")

out_file.close()

笨方法學python

書結構非常簡單,其實就是 52 個習題而已。其中 26 個覆蓋了輸入輸出 變數 以及函式三個課題,另外 26 個覆蓋了一些比較高階的話題,如條件判斷 迴圈 類和物件 測試 以及專案的實現等。每一章節的格式基本都是一樣的,以 練習題開始,讀者照著說明 編寫 不允許複製貼上 執行並檢查結果,然後再做一下...

笨方法學python 一

print i like typing this print this is fun print i said do not touch this.如果用同種引號會報錯 file ex1.py line 8 print i said do not touch this.syntaxerror inv...

學習筆記 笨方法學python

1.1 列表和字典 列表是有一組任意型別的值構成的有序列表,他由方括號構造而成 number list 1,2,3,4 mylist 1,a b 2,4 字典是由一組明值對構成的無序集合,由大括號構造而成 ages 可以通過以下方式訪問列表和字典中的元素 mylist 2 return a ages...