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