首页 > 解决方案 > TypeError:强制转换为 Unicode:需要找到字符串或缓冲区日期时间日期时间

问题描述

这是我将输出保存到csv文件中的脚本:

import os, csv, datefinder, datetime
os.chdir('C:\Users\dul\Desktop\Article')

with open("test2.txt", 'r') as file1:
  text1 = file1.read()

matches = list(datefinder.find_dates(text1))

if len(matches) > 0:
    date = matches[1]
    print date
else:
    print 'No dates found'

csv = open(date, "w")

columnTitleRow = "date, time\n"
csv.write(columnTitleRow)

当我运行此脚本时,我收到以下错误消息:

[回溯(最近一次调用最后一次):文件“C:\Users\dul\Desktop\Article\ap.py”,第 18 行,在 csv = open(date, "w") 类型错误:强制转换为 Unicode:需要字符串或缓冲区,找到日期时间.日期时间]

标签: python

解决方案


您不能将datetime实例传递给open(); 该函数需要一个字符串来指示它应该打开的文件的文件名。

您确定需要打开一个具有日期名称的文件吗?如果确实如此,那么您至少需要将datetime对象转换为 a str

csv = open(str(date), "w")

但我怀疑这真的是你需要的。


推荐阅读