2013-05-13 27 views
2

我剛開始學習python今天。這是一個簡單的腳本,用於讀取,寫入一行或刪除文本文件。它寫入和刪除就好了,但選擇「R」(讀)選項時,我剛剛得到的錯誤:寫入,刪除,但不會讀取文本文件

IOError: [Errno 9] Bad file descriptor

缺少什麼我在這裏......?

from sys import argv 

script, filename = argv 

target = open(filename, 'w') 

option = raw_input('What to do? (r/d/w)') 

if option == 'r': 
    print(target.read()) 

if option == 'd': 
    target.truncate() 
    target.close() 

if option == 'w': 
    print('Input new content') 
    content = raw_input('>') 
    target.write(content) 
    target.close() 

回答

9

您已經以寫入模式打開文件,因此您無法對其執行讀取操作。其次'w'自動截斷文件,所以你的截斷操作是無用的。 您可以使用r+模式在這裏:

target = open(filename, 'r+') 

'r+' opens the file for both reading and writing

打開文件時使用with聲明,它會自動關閉該文件爲您提供:

option = raw_input('What to do? (r/d/w)') 

with open(filename, "r+") as target: 
    if option == 'r': 
     print(target.read()) 

    elif option == 'd': 
     target.truncate() 

    elif option == 'w': 
     print('Input new content') 
     content = raw_input('>') 
     target.write(content) 

由於@abarnert曾建議它會根據用戶輸入的模式打開文件會更好,因爲只讀文件可能會首先引起錯誤,並以'r+'模式排在第一位:

option = raw_input('What to do? (r/d/w)') 

if option == 'r': 
    with open(filename,option) as target: 
     print(target.read()) 

elif option == 'd': 
    #for read only files use Exception handling to catch the errors 
    with open(filename,'w') as target: 
     pass 

elif option == 'w': 
    #for read only files use Exception handling to catch the errors 
    print('Input new content') 
    content = raw_input('>') 
    with open(filename,option) as target: 
     target.write(content) 
+0

完美,謝謝 – AllTheTime1111 2013-05-13 06:58:16

+2

這回答了OP詢問(和很好)。但值得指出的是,根據「選項」,以不同模式打開文件可能會更好。這樣,您就可以讀取CD上的文件。 – abarnert 2013-05-13 08:28:45