我收到来自API的CSV回复。我想将收到的CSV响应附加到我机器中已存在的CSV文件中。我面临的问题是它还附加了第二个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")
答案 0 :(得分: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")
看看这个问题,了解如何使用open, How to open a file using the open with statement
以下是如何比较两个列表(例如标题列表到行列表)的示例, Comparing two lists in Python