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

标签 python

今天刚开始学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()  

最佳答案

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

关于python - 写入、删除,但不会读取文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16516312/

相关文章:

python - 在 PyEphem 中使用地球时间

python setup.py : how to set the path for the generated . 所以

python - Matplotlib - 可以用寄生轴制作子图吗?

python - 如何使用python删除位图图像蒙版中的小岛补丁?

python - QDialog.show()方法有延迟 react

python - 一个函数的类型提示包装另一个函数,接受相同的参数

python - 用户的django默认外键值

python - 字谜Python 3

python 字符串以交替步幅切片

python - python zipfile 是线程安全的吗?