2013-05-13 75 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