希望有人可以帮助我或指出我之前发布的信息正确(我已经搜索了一段时间没有成功),
我对python脚本非常陌生并且正在花时间学习以提高我的技能,但是我在学习时突然需要做以下事情 - 我希望这会帮助我更多地理解Python学习其他地方的基础知识
我有两个具有相同列数据但标题不同的CSV - 示例如下
----$csv1------
ID, FirstName, Surname
1, John, Smith
2, Steve, Davis
, John,Parrot,
4, Dave,Smith
5, Alan, Taylor
----$csv2------
Employee ID, First Name, Given Surname
1, John, Smith
2, Steven, Davis
3, John, Parrott
4, Dave, Allen
6, Mike, Angelo
我的脚本要求是比较2 csv并使用结果创建第3个文件(results.csv)
我知道这是一个很大的问题,但如果有人能提供一些解释来帮助我完成Python之旅,我真的很感激!
谢谢大家。
---- SCRIPT ADDED ------
import csv
CSV1_tuples = []
CSV2_tuples = []
with open("DB1.csv") as CSV2:
csv_CSV2 = csv.reader(CSV2)
for row in csv_CSV2:
CSV2_tuples.append(tuple(row[0:3]))
with open("DB2.csv") as CSV1:
csv_CSV1 = csv.reader(CSV1)
for row in csv_CSV1:
CSV1_tuples.append(tuple(row[0:3]))
if tuple(row[0:3]) in CSV2_tuples:
print(( row[0:3] ), "In both DB1 & DB2")
if tuple(row[1:3]) in CSV2_tuples:
print(( row[0:3] ), "Wrong ID")
答案 0 :(得分:0)
import csv
import re
def get_csv_data(csv_file, row, cell=None):
"""
:param csv_file: Name of csv file
:param row: Row number that you want( counting starts from top to bottom)
:param cell: cell number that you want(counting starts from left to right)
If you give a cell number, the content of that cell will be returned.
If cell =
:return: cell content
"""
ls = []
with open(csv_file, newline='') as csvfile:
csv_file = csv.reader(csvfile, delimiter=' ', quotechar='|')
for rows in csv_file:
ls.append(str(rows[0]).split(","))
if cell is not None:
return re.sub(r'\W+', '', str(ls[row-1]).split(",")[cell-1])
else:
return ls[row-1]
print(get_csv_data('csv1.csv', 2, 2)) #get row 2, cell 2 from csv1 -> returns John
print(get_csv_data('csv1.csv', 2)) #get row 2 from csv1 -> returns a list with all values from the row: [1, 'John', 'Smith']
def write_to_csv(ls):
"""
:param ls: list argument to be written in CSV file
List item will be written as a row, with every list value on a separate cell
:return: None
"""
with open("results.csv", "w") as f:
writer = csv.writer(f)
writer.writerow(ls)
这是从CSV文件获取数据并在另一个文件中写入的方法。您可以进一步实现if语句
row = get_csv_data('csv1.csv', 1) #get first row from csv1.csv, as a list
row.append("Correct") #add the Correct value
write_to_csv(row) #write all row 1 to CSV - will be 1, John, Smith, Correct
答案 1 :(得分:0)
我必须比较两个与示例相似的文件,但只会查看带有 IP 的第 1 列。文件 1(都是文本文件)
file1.txt
IP - MAC 地址 - 端口 - IDF 1 0.2.1.5 00:07:5f:c2:9b:f2 gi1/0/2 2 10.2.1.3 0007.5fc2.9bf4 gi1/0/3 3 10.2.1.7 0007.5fc2.9bf5 gi1/0/4 4
file2.txt
IP - MAC 地址 - 端口 10.2.1.5 0007.5fc2.9bf6 gi1/0/2 10.2.1.9 0007.5fc2.9bf7 gi1/0/2 10.2.1.10 0007.5fc2.9bf8 gi1/0/2
输出文件(result.file)将匹配IP和其余内容所以它只匹配IP并将从文件1结果文件中放置其余内容
10.2.1.5 00:07:5f:c2:9b:f2 gi1/0/2 2 谢谢