[英]Trying to take info from a CSV file, rearrange the columns and then write the new output to a new CSV file in Python
[英]Python csv file - Open a csv file and take all info from 2 columns, get unique values and then remove some replies(without Pandas)
我创建了一个包含 5 列的 csv 文件
Machines | VM | Status | Node | Resolve
我想获取节点和解析下的所有值,找到唯一值,然后删除某些响应(那里有一些我不需要的“无”和“记录”)。
做这个的最好方式是什么?
我试图一次取 1 列,然后将其放入确实有效的集合中,但有更快的方法吗? 然后我试图从集合中拿走我不需要的值,但意识到我最终得到的一些值最后有 \n 。
通常我使用我喜欢的 Pandas,但我目前无法在我正在使用的机器上使用它。
unique3=[]
with open("machines.csv", "r") as file:
mach = file.readlines()
for c in mach:
split_lines = c.split(",")[3]
unique3.append(split_lines)
unique4=[]
with open("machines.csv", "r") as file2:
mach2 = file2.readlines()
for c in mach2:
split_lines2 = c.split(",")[4]
unique4.append(split_lines2)
uniqueunique = (set(unique4 + unique3))
非常感谢任何帮助,我知道这可能是直截了当的,但我在列表和字符串方面遇到了困难
像这样的东西:
import csv
with open("machines.csv", "r") as f:
rdr = csv.reader(f)
next(rdr) # skip header if any, otherwise - remove this line
*_, node, resolve = zip(*rdr)
unique = set(node).union(set(resolve))
print(unique)
然后您可以删除不需要的值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.