我正在從API接收CSV響應。我想將收到的CSV回覆添加到我的機器中已有的CSV文件中。我面臨的問題是它也從第二個CSV文件追加標題。我想刪除該標題。我還附加了我的csv在追加後的外觀截圖。如何在使用python將CSV文件附加到另一個CSV文件時跳過標題
截圖
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")
沒有明顯的直接問題。你有沒有嘗試修復f = open()行?它不屬於你的循環。你可能想要做'appenedFile = actual_file [0];打開(appendFile)爲f:for x ....'。 –
請提供樣本回應(文件)前幾行的摘錄。雖然您已使用切片[1:]跳過第一行響應,但您可能需要跳過多行響應。 – ChuckCottrill
@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