多工位写入CSV文件报错排查:TypeError参数需为字符串而非列表
问题解决:TypeError: write() argument must be str, not list 及其他潜在问题
1. 直接触发错误的原因(第53行)
你在第53行直接调用文件对象的write()方法传入了列表,而文件对象的write()仅接受字符串参数:
with open('//datagrovera.ra.intel.com/DeviceLabUser/Shared/Device lab Error Logger/Error Log.txt', 'a', newline='') as w: w.write([str(1), str(3), str(os.getpid())])
要写入CSV格式的行,必须使用csv.writer的writerow()方法,修改为:
with open(filepath, 'a', newline='') as w: writer = csv.writer(w) writer.writerow([str(1), str(3), str(os.getpid())])
(建议复用已定义的filepath变量,避免重复编写长路径)
2. 锁机制逻辑完全颠倒
当前代码的锁顺序会导致并发写入冲突,正确逻辑应为先抢占锁→写入文件→释放锁,用try-finally确保锁一定会被释放:
# 循环等待锁,用独占创建模式避免竞态条件 while True: try: with open(lockfile, 'x') as w: w.write(str(os.getpid())) break except FileExistsError: time.sleep(1) # 拿到锁后执行写入 try: with open(filepath, 'a', newline='') as w: writer = csv.writer(w) writer.writerow([str(1), str(3), str(os.getpid())]) finally: if os.path.isfile(lockfile): os.remove(lockfile)
3. log()函数未实际写入日志
当前log()仅将数据追加到列表,未写入CSV文件,需补充写入逻辑(结合锁机制):
def log(): global startzeit, time_logs, stat, location, strata_version startzeit = datetime.datetime.today() time_str = startzeit.strftime("%Y-%m-%d %H:%M:%S") time_logs.append(time_str) Error = entry1.get().strip() if not Error: label1.config(text="请输入错误内容") return label1.config(text="Error has been logged") stat.append(Error) location.append(value) strata_version.append(version) # 带锁写入CSV lockfile = filepath + 'lock' while True: try: with open(lockfile, 'x') as w: w.write(str(os.getpid())) break except FileExistsError: time.sleep(0.5) try: with open(filepath, 'a', newline='') as w: writer = csv.writer(w) writer.writerow([time_str, Error, value, version]) entry1.delete(0, tk.END) finally: if os.path.isfile(lockfile): os.remove(lockfile)
4. 模块名被覆盖的问题
你先import time,又定义了time = [],导致time.sleep()调用失败,建议修改列表变量名:
# 替换原time = [] time_logs = []
5. 冗余的全局变量声明
函数外的global currenttime无意义,global关键字应在函数内部使用:
def timer(): global currenttime currenttime = datetime.datetime.today() window.after(1000, timer)
内容的提问来源于stack exchange,提问作者Marshmellow Physics
相关产品推荐
相关产品推荐

