我想创建一个用户凭据Python脚本,其中数据存储在CSV文件中,并且用户应为唯一
我想创建一个用户凭证Python脚本,其中数据存储在CSV文件中,并且用户应该是唯一的。我正在获得具有相同数据输入的CSV文件中一遍又一遍地显示的重复值。我尝试了所有可能的方法,但并未显示结果。 My code is below:
def create_credentials(self, user_id, username, publisher, display_name):
with open('file_1.csv', 'r+') as file_open:
# creating a csv reader object
existing_users = csv.reader(file_open)
for i in existing_users:
print(i)
# To check if a user exists with the same data or not.
if user_id in existing_users:
print("Sorry User ID already exists in file")
else:
if user_id == '':
user_id = input("Enter a valid user id")
self.__user_id = user_id
if username not in existing_users:
if username == '':
username = input("Enter a valid username")
self.__username = username
else:
print("Sorry Username already exists")
The indentation is correct in my code, it is looking a bit distorted here.我想制作唯一的记录,而不会获得重复的记录,如果我尝试创建重复记录,它应该给我一个错误或print()消息,说明记录已经存在于文件中。另外,我尝试在Internet上进行一些检查,然后知道该文件没有加载我猜的所有数据。有人可以帮我吗?提前。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
此代码读取CSV文件,但不记得它。您需要将用户名和ID存储在读者上时,以便以后可以使用它们。 Here's your code:
Looking at the documentation,
我们看到CSV.Reader返回一个读取器对象,该对象将在给定的CSVFILE中迭代。
但是迭代器只能读一次:
https://docs.python.org/3/3/3/tutorial/tutorial/classes.html# iterators
Since it iterated over the full csv file in this code, it is done.从“现有_users”中读取的任何进一步尝试都会导致停止迭代异常,这就是您在“使用”中会发生的情况。
This code reads the csv file, but doesn't remember it. You'll want to store the usernames and id's as you iterate over the reader so you can use them later. Here's your code:
Looking at the documentation,
https://docs.python.org/3/library/csv.html#csv.reader
we see that csv.reader returns a reader object which will iterate over lines in the given csvfile.
But an iterator can only be read once:
https://docs.python.org/3/tutorial/classes.html#iterators
Since it iterated over the full csv file in this code, it is done. Any further attempt to read from "existing_users" will result in a stop iteration exception, which is what happens when you use "in".