Skip to main content
 首页 » 编程设计

python之在 Windows 上编写 CSV

2025年05月04日10EasonJim

我编写的脚本在我的 Mac 上运行良好,但在我的 Windows 计算机(需要运行它的地方)上运行不佳。我正在尝试附加到 CSV。片段:

with open('timeclock.csv', 'a') as timeclocklog: 
    timeclockwriter = csv.writer(timeclocklog) 
    timeclockwriter.writerow([now, inorout]) 

当我尝试这样做时,我的 CSV 中没有附加任何行。如果我将 a 更改为 ab,我会被告知“str 不支持缓冲区接口(interface)”。好的,所以我想我需要以某种方式将我的字符串转换为字节,但我似乎无法到达那里。它不需要允许任何奇怪的字符——唯一允许的输入是单词“in”或“out”。

有什么想法吗?谢谢!

更新:

这是 CSV 结构:

TIMESTAMP,IN-OUT 
Tue Apr 15 10:23:05 2014,in 

脚本允许的唯一输入是“in”或“out”:

if (inorout.lower() == 'in') or (inorout.lower() == 'out'): 
    # Do the stuff 

杰里米

请您参考如下方法:

这对我来说很好:

import csv 
now = 'Tue Apr 15 10:23:05 2014' 
inorout = 'out' 
 
with open('timeclock.csv', 'a', newline='') as timeclocklog: 
    timeclockwriter = csv.writer(timeclocklog) 
    timeclockwriter.writerow([now, inorout])