我创建了一个名为目录路径+当前日期和时间的txt文件。发生以下错误:
无法打开文件。强制转换为Unicode:需要字符串或缓冲区, 找到NoneType
def create_file(count):
filename = "countMetrics"
dir = os.getcwd()
#print 'Current directory path is-'
#print dirPath
date = datetime.datetime.now()
now = date.strftime("%Y-%m-%d %H:%M")
#print 'current date and time is-'
#print now
## date and time representation
#print "Current date & time " + time.strftime("%c")
dirPath = os.path.join(dir, filename)
filenameCreated = dirPath+now+".txt"
#filenameCreated = dirPath+filename+now+".txt"
print filenameCreated
f = openfile(filenameCreated,'a')
return f
#writeFile(f,count)
#defining openfunction
def openfile(filename,mode):
try:
open(filename,mode)
except Exception, err:
print("File cannot be opened.")
print(str(err))
return
def readFile(filename):
try:
target = open(filename,'r')
content=filename.read() # reading contents of file
for line in target:
print content
target.close()
except:
print "File is empty.."
return
#defining write function
def writeFile(filename,count):
try:
target = openfile(filename,'a')
target.write(count)
target.close()
except Exception, err:
print("File have no data to be written.")
print(str(err))
return
答案 0 :(得分:0)
您的openfile
函数未返回任何内容。更改它以返回打开的文件描述符,您的代码可能会起作用: - )
def openfile(filename, mode):
try:
return open(filename, mode)
except Exception as err:
print "File cannot be created", err
return
在主代码中添加一个if来检查是否收到文件描述符。
f = openfile(filenameCreated,'a')
if not f:
print "No file created"
return
return f
你的writeFile函数将是这样的:
def writeFile(target, count):
try:
target.write(count)
target.close()
return 1
except Exception as err:
print "Cannot write into the file"
return 0
因为你的openfile本身会返回一个描述符。你不需要创建另一个。