2

我今天刚开始学习python。这是一个简单的脚本,用于读取、写入一行或删除文本文件。它可以很好地写入和删除,但是在选择“r”(读取)选项时,我会收到错误消息:

IOError: [Errno 9] 错误的文件描述符

我在这里错过了什么......?

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()  
4

1 回答 1

9

您已以写入模式打开文件,因此无法对其执行读取。其次'w'自动截断文件,因此您的截断操作是无用的。您可以r+在此处使用模式:

target = open(filename, 'r+')

'r+' 打开文件进行读写

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)
于 2013-05-13T06:53:18.340 回答