我有一个Excel文件(我将其作为csv导出)我要解析,但我找不到最好的方法来解决它. csv是我的网络中的计算机列表,以及每个帐户在本地管理员组中的帐户.我已经用元组做了类似的事情,但是每台计算机的帐户数量从1到30不等.我想建立一个列表列表,然后浏览每个列表以查找应该存在的帐户(管理员等)然后删除它们,这样我就可以导出一个不应该是本地管理员的帐户列表,但是. csv文件的格式如下:
"computer1" Administrator localadmin useraccount "computer2" localadmin Administrator "computer3" localadmin Administrator user2account
任何帮助,将不胜感激
编辑:这是我正在使用的代码
import csv import sys #used for passing in the argument file_name = sys.argv[1] #filename is argument 1 with open(file_name,'rU') as f: #opens PW file reader = csv.reader(f) data = list(list(rec) for rec in csv.reader(f,delimiter=',')) #reads csv into a list of lists f.close() #close the csv for i in range(len(data)): print data[i][0] #this alone will print all the computer names for j in range(len(data[i])) #Trying to run another for loop to print the usernames print data[i][j]
问题在于第二个for循环.我想能够阅读每一行,现在,只需打印它们.
解决方法
这应该让你走上正轨:
import csv import sys #used for passing in the argument file_name = sys.argv[1] #filename is argument 1 with open(file_name,')) #reads csv into a list of lists for row in data: print row[0] #this alone will print all the computer names for username in row: #Trying to run another for loop to print the usernames print username
最后两行将打印所有行(包括“计算机”).做
for x in range(1,len(row)): print row[x]
…避免两次打印计算机.
请注意,使用“with”构造时不需要f.close(),因为退出“with”块时资源将自动关闭.
就个人而言,我会这样做:
import csv import sys #used for passing in the argument file_name = sys.argv[1] #filename is argument 1 with open(file_name,'rU') as f: #opens PW file reader = csv.reader(f) # Print every value of every row. for row in reader: for value in row: print value