FW=open('FILE01.txt','w') s='I am in Tunghai University.' FW.write(s) FW.close() |
在工作的目錄之下應該有一個檔案FILE01.txt被產生, 並且寫入的資料就是我們在程式中所寫入的字串。 |
將上面產生的檔案打開,再寫入兩行文字之後存檔,然後在下面的程式中, 我們把這個經過修改之後的檔案讀進程式中,然後將資料打印在螢幕上, 確認我們的修改確實在檔案讀入的時候正確讀入程式當中。 FR=open('FILE01.txt','r') a=FR.read() print(a) |
I am in Tunghai University. Hello. I am learning AI. |
FW=open('FILE02.txt','w') for i in range(1,11): s=str(i)+' '+str(i**2) print(s) FW.write(s+'\n') FW.close() |
1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100 |
FR=open('FILE02.txt','r') a=FR.read() b=a.split() N=len(b) y=[] for i in range(1,N,2): y.append(int(b[i])**2) print(y) FW=open('FILE03.txt','w') for i in range(len(y)): s=b[i*2]+' '+str(y[i]) print(s) FW.write(s+'\n') FW.close() |
[1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000] 1 1 2 16 3 81 4 256 5 625 6 1296 7 2401 8 4096 9 6561 10 10000 |