【问题标题】:Writes, Deletes, but won't read text file写入,删除,但不会读取文本文件
【发布时间】:2013-05-07 03:33:19
【问题描述】:

我今天刚开始学习python。这是一个用于读取、写入一行或删除文本文件的简单脚本。它写入并删除了很好,但是在选择'r'(read)选项时,我只需收到错误:

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

【问题讨论】:

    标签: python


    【解决方案1】:

    您已以写入模式打开文件,因此无法对其执行读取。其次'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)
    

    【讨论】:

    • 这回答了 OP 的要求(并且非常好)。但值得指出的是,根据option 以不同的模式打开文件可能会更好。这样,您就可以读取 CD 上的文件。
    猜你喜欢
    • 2017-02-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-23
    • 2016-10-06
    • 1970-01-01
    • 2013-05-18
    • 2012-09-15
    • 2012-03-08
    相关资源
    最近更新 更多