Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python for循环未运行_Python_Python 2.7_Csv_For Loop - Fatal编程技术网

Python 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)

我正在写一个包含id的简单命令行程序,我想让它在每次运行函数时都能为CSV文件添加一个值。我做了一个我认为有效的函数,但显然不行。我的一个for循环运行不正确;(这是我的密码:

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
,因为这是一种内置数据类型