2017-06-19 63 views
1

我正在從API接收CSV響應。我想將收到的CSV回覆添加到我的機器中已有的CSV文件中。我面臨的問題是它也從第二個CSV文件追加標題。我想刪除該標題。我還附加了我的csv在追加後的外觀截圖。如何在使用python將CSV文件附加到另一個CSV文件時跳過標題

截圖

click here to see the screenshot screenshot of the response recieved 我想這個代碼

response = requests.get(Link) 
actual_file = glob.glob(path_to_data+'\\Data\\*') 
new_target_file = path_to_data+'\\Data'+'\\'+State+'_'+date+'_'+St_Id+'.csv' 
# Write to .CSV 
if not os.path.exists(new_target_file): 
    for x in response.text.split('\n')[1:]: 
     f = open(actual_file[0], "a") 
     f.write(x) 
    f.close() 
    os.rename(actual_file[0],new_target_file) 
else: 
    logging.warning("File already exist") 
+0

沒有明顯的直接問題。你有沒有嘗試修復f = open()行?它不屬於你的循環。你可能想要做'appenedFile = actual_file [0];打開(appendFile)爲f:for x ....'。 –

+0

請提供樣本回應(文件)前幾行的摘錄。雖然您已使用切片[1:]跳過第一行響應,但您可能需要跳過多行響應。 – ChuckCottrill

+0

@CharlesMerriam我試過你的方法。它將刪除標題,但它只向文件附加1行。這裏是代碼'response = requests.get(Link) actual_file = glob.glob(path_to_data +'\\ Data \\ *') new_target_file = path_to_data +'\\ Data'+'\\'+ State +'_'+日期+ '_' + St_Id + 'CSV' appendedfile = actual_file [0] #寫入到.csv 如果不是os.path.exists(new_target_file): 開放(appendedfile, 「A」)爲f: 爲x in response.text.split('\ n')[1:]: f.write(x)' – PriyalChaudhari

回答

0

你的問題是識別響應,行跳過其中,併線保留。假設實際內容在第二行開始,您已經實施切片以在第一行之後提取響應行。根據你描述的症狀,這不是(總是)的情況。

#fully describe header here, 
header="STATION,STATION_ELEVATION,LATITUDE,LONGITUDE,..." 

def isheader(line,header,delim=','): 
    l = line.split(delim) #may want to fold case 
    h = header.split(delim) #may want to fold case 
    n = sum(list(set(l) & set(h))) 
    return n==len(h) 

response = requests.get(Link) 
actual_file = glob.glob(path_to_data+'\\Data\\*') 
new_target_file = path_to_data+'\\Data'+'\\'+State+'_'+date+'_'+St_Id+'.csv' 
# Write to .CSV 
if not os.path.exists(new_target_file): 
    with open(actual_file[0], "a") as f: 
     for x in response.text.split('\n')[1:]: 
      if len(x) < 2: continue #skip empty lines 
      if isheader(x,header,','): continue #skip header 
      f.write(x+'\n') 
    #with performs close automatically 
    os.rename(actual_file[0],new_target_file) 
else: 
    logging.warning("File already exist") 

看看這個問題如何開放使用, How to open a file using the open with statement

下面是如何比較兩個列表(如標題列表的行列表)爲例, Comparing two lists in Python

+0

'f.write(x +'\ n')'這就解決了我的代碼中的問題。我也會嘗試你的接受。感謝您的迴應。 – PriyalChaudhari

相關問題