写入,删除,但不会读取文本文件

All*_*111 2 python

我今天刚开始学习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()  
Run Code Online (Sandbox Code Playgroud)

Ash*_*ary 9

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

target = open(filename, 'r+')
Run Code Online (Sandbox Code Playgroud)

'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)
Run Code Online (Sandbox Code Playgroud)

正如@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)
Run Code Online (Sandbox Code Playgroud)

  • 这回答了OP所要求的(非常好).但值得指出的是,根据`option`以不同的模式打开文件可能更好.这样,您可以,例如,读取CD上的文件. (2认同)