Write and Read from a file in Python

2011年11月22日 星期二

Write and Read from a file in Python



昨天在網路上看到某位大大教學如何寫檔與讀檔
但是他的舊方式會造成 IOError: Errno 0 Error
照他的舊方式我重新在Python 3.2.1中試了一下
發現read檔案時會發生無法印出的問題
還有就是寫檔時會寫成binary的格式
之後就追蹤一下程式碼 並且研究一下和之前看到的範例有何差別
最後發現是 讀檔時若用a+方式 會讀不到檔案 要改用r+
底下是將其的程式碼稍做修改後 就可以正確印出和寫入



#!/usr/bin/python
import os,time,sys

Org_Sub = 'abc'
sSub = 'def'

SaveDirectory = os.getcwd()
filename = os.path.join(SaveDirectory,"poem.txt")

try:
   
    f = open(filename,"r+")
    print(filename)
    Log_file = f.read()   
    print(Log_file)
   
except:
    print(filename, sys.exc_info())

sData =Org_Sub  + sSub
f.write(str(sData))
f.close()


如有寫錯的地方請幫忙指正~感恩!


0 意見 :

張貼留言