2016-09-19 100 views
-1
def rowfilter(): 
    field_data = {} 
    try: 
     csv_read = csv.reader(open('sample.csv',), delimiter=',', quotechar='|') 
     for row in csv_read: 
      for field in row[7]: 
       print(field)  


    except FileNotFoundError: 
      print("File not found") 

rowfilter() 

該代碼運行成功,但我希望此代碼在user_input之前打印數據。 例如如果用戶輸入5,那麼它應該打印從1到5的所有細節以及與其關聯的所有列。如何從Python中的CSV文件讀取列

回答

0
def rowfilter(col1, col2): 

    try: 
     csv_read = csv.reader(open('items.csv'), delimiter=',', quotechar='|') 
     for row in csv_read: 
     print(row[int(cols[0]):int(cols[1])]) 

    except FileNotFoundError: 
      print("File not found") 

inputrows = input("Enter columns in the format: col1 col2 ") 
rowfilter(inputrows.split())) 

我已編輯這個答案按你的評論,就可以處理CSV行作爲一個列表,一旦CSV讀者已經閱讀。因此,此方法會將列col1打印到col2。請注意,python是0索引。

+0

工作如何從表USER_INPUT讀取特定/特定的列。例如,我需要所有列的行值從3開始到n .. –

+0

我按照您的要求編輯了我的答案。 –

0

這是幾乎可以肯定pandas

import pandas as pd 

df = pd.read_csv('sample.csv', delimiter=',', quotechar='|') 

#you can get the 7th column like this 
df_seven = df[df.columns[7]] 

#Then slice the dataframe as you see fit 
df_seven[0:5] # first five rows 
df_seven[4:9] # rows 4 to 9... etc 
+0

似乎熊貓不會在py3.3中工作。 –

+0

在python3.5中完美適用於我 – JoshuaBox