簡體   English   中英

如何使用python將CSV文件附加到另一個CSV文件時跳過該文件的標題

[英]How to skip header of CSV file while appending it to another CSV file using python

我收到了來自API的CSV回復。 我想將收到的CSV響應附加到我機器中已存在的CSV文件中。 我面臨的問題是它還附加了第二個CSV文件的標題。 我想刪除該標題。 我還附上了追加后我的csv看起來的截圖。

截圖

點擊這里查看截圖 收到回復的截圖我正在嘗試此代碼

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")

您遇到的問題是識別響應,要跳過的行以及要保留的行。 您已經實現了切片以在第一行之后提取響應行,假設實際內容在第二行開始。 根據您描述的症狀,這不是(總是)情況。

#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")

看一下這個問題,了解如何使用open, 如何使用open with語句打開文件

下面是一個如何比較兩個列表(例如標題列表和行列表)的示例, 比較Python中的兩個列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM