Python for循环未运行
我正在写一个包含id的简单命令行程序,我想让它在每次运行函数时都能为CSV文件添加一个值。我做了一个我认为有效的函数,但显然不行。我的一个for循环运行不正确;(这是我的密码:Python for循环未运行,python,python-2.7,csv,for-loop,Python,Python 2.7,Csv,For Loop,我正在写一个包含id的简单命令行程序,我想让它在每次运行函数时都能为CSV文件添加一个值。我做了一个我认为有效的函数,但显然不行。我的一个for循环运行不正确;(这是我的密码: def addId(id): file = open(ID_FILE_PATH, 'wb+') read = csv.reader(file) write = csv.writer(file) existingRows = [] existingRows.append(id)
def addId(id):
file = open(ID_FILE_PATH, 'wb+')
read = csv.reader(file)
write = csv.writer(file)
existingRows = []
existingRows.append(id)
for rows in read: # This does not run
print rows
if len(rows) > 0 and rows[0] not in existingRows:
existingRows.append(rows[0])
for rows in existingRows: # This runs
write.writerow([rows])
file.close()
抱歉我的英语不好。顺便说一句。您打开文件时使用:
file = open(ID_FILE_PATH, 'wb+')
:
请注意,“w+”会截断文件
您截断了文件,所以难怪没有什么可读取的!请改用
rb+
。问题很可能是您在同一文件对象上同时打开了csv.reader和csv.writer。请参见类似的问题。此外,您不应该命名变量file
,因为这是一种内置数据类型