python多次open 问题 'w+','a+'不能连续使用吗?


t1=open(filename,'w+')

line1=input('please type some code'+'\n'+'>')
line2=input('type someother code'+'\n'+'>')

t1.write(line1+'\n')
t1.write(line2)

print(t1.readline())
print(t1.read())

t0=open(t1,'a+')
line3=input('please append some code'+'\n'+'>')


TypeError: invalid file: <_io.TextIOWrapper name='testing.txt' mode='w+' encoding='UTF-8'>

q1/以'w'模式open了一个文件,如果再次以某种模式(例如本文打'a+'模式)open,需要怎么做?还是说,python根本不支持连续open?我是刚学python,知道很少。
我同学说,先 close,那显然不行啊,close后不能再对文件进行任何操作了。
我的目标是先open(filename,'w+')写入两行字符串line1 line2,然后再追加line3.

这个题目是我自己随便写的,目的是为了练习。

阅读 4.5k
4 个回答

open 的参数传错了,所以报的错,传的应该是个文件路径,应该是个 str 类型的。

我的目标是先open(filename,'w+')写入两行字符串line1 line2,然后再追加line3.

你可以试下:

t1=open(filename,'w+')

t1.write(line1)
t1.write(line2)

t0=open(filename,'a+')
t0.write(line3)
t1.close()
t0.close()

open 参数是文件path,后面open的参数t1已经是文件对象了

clipboard.png

强烈建议:文件open配合close使用,或者使用with持有文件对象

直接用a+也会新建文件

建议直接用with open()来操作。
你同学说的没错,先close,之后要写再open

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题