python-3.x 检查CSV中的行,如果不存在-请附加该行

xu3bshqb  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(162)

我有以下问题。
我正在尝试将CSV文件的所有现有行与当前行进行匹配。
如果该行已经存在,脚本应该只显示它存在。
如果该行不存在,脚本应该告诉我该行不存在。
但是,脚本总是告诉我该行不存在,即使我已经检查该行确实存在。
以下是我目前为止的代码:

# Imports from Library(s)
from pathlib import Path
import csv
from windows_tools.installed_software import get_installed_software

# Check if the csv file exists - if not: create it
path = Path('./programms.csv')
existingFile = []
if path.is_file() is not True:
    with open('programms.csv', 'w', newline='') as write1:
        w_object = csv.writer(write1)
        w_object.writerow(["Name", "Version", "Publisher"])
        write1.close()

# Lists all Software on the computer
for software in get_installed_software():
    csv_list = (software['name'], software['version'], software['publisher'])
    
    with open('programms.csv', 'r') as f1:
        existingFile = [line for line in csv.reader(f1, delimiter=',')]
    f1.close()

    #Checks if 
    if csv_list in existingFile:
        print(str(csv_list) + "already is in the list") 
        continue

    if csv_list not in existingFile:
        print("Current Object is not in the Existing lines")

    #     # Open our existing CSV file in append mode
    #     # Create a file object for this file
    #     with open('programms.csv', 'a', newline='') as append1:

    #     # Pass this file object to csv.writer() and create writer_object
    #         writer_object = csv.writer(append1)
        
    #         # Pass the list as an argument intothe writerow() 
    #         writer_object.writerow(csv_list)
    #         # Close the file object
    #         append1.close()
            
print (existingFile)

我已经尝试指定要检查的类型:if str(csv_list) in list(existingFile):遗憾的是,我刚刚开始使用python,我不太确定如何处理这个问题。

ni65a41a

ni65a41a1#

这就是检查列表是否在csv中的方法(转换为列表的列表)注意Python返回false:“1”== 1您需要确保csv中的类型与要检查的列表中的类型匹配

import csv

'''
test.csv:"
1,2,3,4,5
2,3,4,5,6
3,4,5,6,7
4,5,6,7,8
"
'''
with open('test.csv', 'r') as f:
  
    # Return a reader object which will
    # iterate over lines in the given csvfile
    csv_reader = csv.reader(f, delimiter=',')
  
    # convert string to list
    list_of_csv = list(csv_reader)
  
    print(list_of_csv)

test = [1,2,3,4,5]
if test in list_of_csv:
    print("IS IN LIST")
else:
    print("NOT IN LIST")
#The above will print NOT IN LIST because the test list is a list of ints, and the csv list is a list of strings

test2 = ["1","2","3","4","5"]
if test2 in list_of_csv:
    print("IS IN LIST")
else:
    print("NOT IN LIST")
#Above will print IS IN LIST because the list has strings in it not ints
3qpi33ja

3qpi33ja2#

多亏了你,我修好了它!
尝试csv_list =[软件["名称"],软件["版本"],软件["发布者"]]-inspectorG4dget
以及
将csv_list设置为元组,而不是列表,因为使用的是()而不是[]-Barmar
我是对的!我只是把元组改成了一个列表,就这样了。感谢所有的回复这么快!
致上
普吕阿杜斯

相关问题