3.python檔案操作及異常處理

wsc449發表於2018-02-07
#python檔案操作
#python程式對檔案進行開啟,關閉,讀取,寫入操作
#檔案的開啟路徑  開啟方式r w wb(二進位制方式寫入)
#新建檔案  或者開啟檔案
fh1=open("/Users/xubin/myapp/pythonfile/file1.txt","w")
fh2=open("/Users/xubin/myapp/pythonfile/file2.txt","w")

#寫入檔案
contents1="檔案內容如下"
fh2.write(contents1)
fh1.write(contents1)

#讀檔案內容
fh3=open("/Users/xubin/myapp/pythonfile/file3","r")
#data=fh3.readline()
#print(data)

while True:
    line=fh3.readline()
    if(len(line)==0):
        break
    print(line)

fh1.close()
fh2.close()
fh3.close()

#python實現從檔案file3,將其中的檔案寫入到file4.txt中
fh3=open("/Users/xubin/myapp/pythonfile/file3","r")
fh4=open("/Users/xubin/myapp/pythonfile/file4.txt","w")

while True:
   line=fh3.readline()
   fh4.write(line)
   if(len(line)==0):
        break
   print(line)
fh3.close()
fh4.close()

#python異常值處理
#python程式在執行的時候,經常會遇到異常,如果中間異常不處理,經常會導致程式崩潰!
#比如後面寫爬蟲的時候,如果不進行異常處理,很可能蟲爬了一半,直接崩潰了!

print("xubin")
try:
    printsfs("xubin1")
except Exception as error:
    print(error)  #print(error)
    print("hello")


相關文章