如何在使用python将CSV文件附加到另一个CSV文件时跳过标题
问题描述:
我正在从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")
答
你的问题是识别响应,行跳过其中,并线保留。假设实际内容在第二行开始,您已经实施切片以在第一行之后提取响应行。根据你描述的症状,这不是(总是)的情况。
#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
没有明显的直接问题。你有没有尝试修复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