为什么python open()写不了文件?

为什么python open()写不了文件?文件打开后一片空白,close()后也没有用。源代码如下:

def event(dirpath,name):
    #./user/XXXX/XX/XX/...目录下的统计文件
    alldir=open(dirpath+'//eventall.txt','w+',encoding='UTF-8')
    if alldir.read() == '':
        alldir.write('0,0')
        alldir.close()
        del alldir
        alldir=open(dirpath+'//eventall.txt','w+',encoding='UTF-8')
        r=alldir.read()
        print(r)
        alldir.write(str(sum(list(map(float,r.split(','))))+list(float(name)))+',0')
        alldir.close()
        del alldir
event('整理','4')

运行后报错:

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\新建文本文档 (2).py", line 14, in 
    event('整理','4')
  File "C:\Users\Administrator\Desktop\新建文本文档 (2).py", line 11, in event
    alldir.write(str(sum(list(map(float,r.split(','))))+list(float(name)))+',0')
ValueError: could not convert string to float: ''

img

但是后来才发现是文件一片空白,大家能帮忙看一下吗

你的代码中间有个del alldir,再次打开后就是空的r是空的,map(float,r.split(',')),所以就会出现你现在的错误。你本意是想分割0,0的
还有你的list(float(name)),这个写法也是错误,再说前面sum计算以后是float,加后面list,能加吗?

alldir.write(str(sum(list(map(float,r.split(','))))+float(4))+',0')

望采纳!!!

应该是你的文件里面有空格,才出错的,你看报错空格字符串转换报错。

把文件里面的空格删除。

另外,请检查一下自己的字符串内容,注意里面是否有换换行符 \n,制表符 \t 或空字符串 ‘ ’
如果有,请删除!