繁体   English   中英

如何使用python将唯一值写入CSV

[英]How to write a unique value to a csv with python

我试图将唯一的值写入其中已经有一个int列表的csv。

目前,我试图遍历一系列可能的数字,然后检查这些数字是否在csv中。 看来检查工作不正常。

def generateUserCode():
    with open ('/MyLocation/user_codes.csv') as csvDataFile:
        userCodes = csv.reader(csvDataFile)
        for x in range(0, 201):
            if x not in userCodes:
                return x

def writeUserCode(userCode):        
    with open ('/MyLocation/user_codes.csv', 'a') as csvDataFile:
        csvDataFile.write('\n' + str(userCode))

userCode = generateUserCode()
writeUserCode(userCode)   

因此,它应打印不在csv中的第一个数字,并将其添加到csv中。 但是,它所做的就是打印0并在每次运行时将0添加到我的csv中,即使csv中有0。

更新:

csv看起来像这样:

3
4
5
35
56
100

值更多,但通常是相同的,没有重复,并且值在0到200之间

在没有看到CSV的情况下进行回答很棘手,但是当您阅读CSV时,所有字段都是字符串。 因此,您需要将userCodes转换为intx转换为string才能进行比较。

例如:

userCodes = [int(d[0]) for d in csv.reader(csvDataFile)]
for x in range(0, 201):
    if x not in userCodes:
        return x

您正在检查str是否在csv.reader的实例中。 即使使用普通文件句柄,此语法也不起作用:

with open('somefile.txt') as fh:
    x = fh.read()

 x
'Spatial Reference: 43006\nName: Jones Tract\n424564.620666, 4396443.55267\n425988.30892, 4395630.01652\n426169.09473, 4395426.63249\n426214.291182, 4395268.4449\n\nName: Lewis Tract\n427909.158152, 4393935.14955\n428587.104939, 4393731.76552\n428700.096071, 4393528.38148\n428745.292523, 4393347.59567\n\nName: Adams Tract\n424180.450819, 4393957.74778\n424361.236629, 4393709.16729\n424655.013571, 4393641.37261\n424858.397607, 4393776.96197\n'

# now check if 'e' is in fh

with open('somefile.txt') as fh:
    'e' in fh

False

'e' in x
True

另外,您的csv文件不是真正的csv文件,因此我只使用普通的文件句柄,而完全忽略了csv。

更好的方法可能是将代码汇总到一set然后从中进行检查:

def get_codes():
    with open('user_codes.csv') as fh:
        # return a set to test membership quickly
        return {line.strip() for line in fh}

codes = get_codes()

def add_code(code):
    if code not in codes:
        codes.add(code)
        with open('user_codes.csv', 'a') as fh:
            fh.write(code)
    else:
        raise ValueError("Code already exists")
        # or do something else

add_code(88)
add_code(88)
# ValueError

要自动生成用户代码,因为您正在使用range ,这变得相对容易:

def generate_user_code():
    try:
        # this returns the first number not in codes
        return next(i for i in range(201) if i not in codes)
    except StopIteration:
        # you've exhausted your range, nothing is left
        raise ValueError("No unique codes available")

# and your write method can be changed to
def add_code(code):
    with open('user_codes.csv', 'a') as fh:
        codes.add(code)
        fh.write(code)


codes = get_codes()
user_code = generate_user_code()
add_code(user_code)

迭代userCodes显示每个项目都是一个字符串列表:

 for x in userCodes:
     print(x)

返回:

 ['3']
 ['4']
 ['5']
 ['35']
 ['56']
 ['100']

因此,有很多可能的修复方法,其中一个是:

def generateUserCode():
    with open ('/MyLocation/user_codes.csv') as csvDataFile:
        userCodes = csv.reader(csvDataFile)
        userCodes = [int(item[0]) for item in userCodes]
        for x in range(0, 201):
            if x not in userCodes:
                return x

问题在于以下行:

if x not in userCodes:

userCodes不是列表,而是csvReader对象。 另外,您应该使用

if str(x) not in line:
#use str(x) instead of x

这是对我有用的代码:

import csv
def generateUserCode():
    with open ('file.csv') as csvDataFile:
        csvread = csv.reader(csvDataFile)
        userCodes = []
        #print(userCodes)
        for line in csvread:
            try:
                userCodes.append(line[0]) # As long as the code is the first  
                                          # element in that line, it should work
            except:
                IndexError # Avoid blank lines
        print(userCodes)
        for x in range(0, 201):
            if str(x) not in userCodes:
                return x

def writeUserCode(userCode):
    with open ('file.csv', 'a') as csvDataFile:
        csvDataFile.write('\n' + str(userCode))

userCode = generateUserCode()
writeUserCode(userCode)

您可以尝试这样做:

....
userCodes = csv.reader(csvDataFile)
uc = []
for y in userCodes:
    uc += y
for x in range(0, 201):
    if str(x) not in uc:
        return x
....

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM