我今天刚开始学习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()
答案 0 :(得分: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)