本文介绍了Python:使用Excel CSV文件只读某些列和行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 虽然我可以读取csv文件,而不是读取整个文件如何仅打印某些行和列?While I can read csv file instead of reading to whole file how can I print only certain rows and columns?想象一下,就好像这是Excel:Imagine as if this is Excel: A B C D EState |Heart Disease Rate| Stroke Death Rate | HIV Diagnosis Rate |Teen Birth RateAlabama 235.5 54.5 16.7 18.01Alaska 147.9 44.3 3.2 N/AArizona 152.5 32.7 11.9 N/AArkansas 221.8 57.4 10.2 N/ACalifornia 177.9 42.2 N/A N/AColorado 145.3 39 8.4 9.25我有什么:import csvtry: risk = open('riskfactors.csv', 'r', encoding="windows-1252").read() #find the fileexcept: while risk != "riskfactors.csv": # if the file cant be found if there is an error print("Could not open", risk, "file") risk = input("\nPlease try to open file again: ")else: with open("riskfactors.csv") as f: reader = csv.reader(f, delimiter=' ', quotechar='|') data = [] for row in reader:# Number of rows including the death rates for col in (2,4): # The columns I want read B and D data.append(row) data.append(col) for item in data: print(item) #print the rows and columns我只需要阅读列B和D,所有的统计信息就像这样读取:I need to only read column B and D with all statistics to read like this: A B D State |Heart Disease Rate| HIV Diagnosis Rate | Alabama 235.5 16.7 Alaska 147.9 3.2 Arizona 152.5 11.9 Arkansas 221.8 10.2 California 177.9 N/A Colorado 145.3 8.4 已编辑 没有错误Editedno errors有什么想法来解决这个问题?我尝试的一切都不行。任何帮助或建议非常感激。Any ideas on how to tackle this? Everything I try isn't working. Any help or advice is much appreciated.推荐答案如果你仍然坚持,你真的没有理由使用CSV模块将文件作为所有CSV文件只是逗号分隔的字符串。所以,对于一些简单的事情,你可以尝试这个,这将给你一个表格元素(状态,心脏病率,艾滋病诊断率)的列表。If you're still stuck, there's really no reason you have to read the file with the CSV module as all CSV files are just comma separated strings. So, for something simple you could try this, which would give you a list of tuples of the form (state,heart disease rate,HIV diagnosis rate)output = []f = open( 'riskfactors.csv', 'rU' ) #open the file in read universal modefor line in f: cells = line.split( "," ) output.append( ( cells[ 0 ], cells[ 1 ], cells[ 3 ] ) ) #since we want the first, second and third columnf.close()print output只需要注意,如果您想进行任何数据分析,您将不得不通过并忽略标题行。Just note that you would then have to go through and ignore the header rows if you wanted to do any sort of data analysis. 这篇关于Python:使用Excel CSV文件只读某些列和行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
09-06 03:02