Python:删除 CSV 标题行并重写新标题行
仍在自学 python,所以如果我的代码很糟糕,请不要恨我...
我的代码:
ifile = csv.reader(open("TE.csv",'rb'))
shutil.copy("TE.csv","temp")
tempfile = csv.reader(open("temp","rb"))
ofile = csv.writer(open("TE-RESULTS.csv","ab"))
for row in ifile:
#do some web scraping stuff here
VC_s = str(cells[1].find(text=True))
VC_i = str(cells[2].find(text=True))
VT_s = str(cells[4].find(text=True))
entry = [VC_s, VC_i, VT_s]
rowAdd = tempfile.next()
ofile.writerow(rowAdd + entry)
问题:我从一个 CSV 开始,我必须在末尾添加 3 列。使用上面的代码,我得到以下输出:
HEADER1 HEADER2 HEADER3 result1 result2 result3
autocheck C:\check 1.jpg result1 result2 result3
services C:\svcs 2.jpg result1 result2 result3
My DESIRED 输出:
HEADER1 HEADER2 HEADER3 HEADER4 HEADER5 HEADER6
autocheck C:\check 1.jpg result1 result2 result3
services C:\svcs 2.jpg result1 result2 result3
修复我的代码以提供所需输出的最佳方法是什么?我最初的想法是删除 HEADERS 行并将其替换为 TE-RESULTS.csv 文件中的新 HEADERS 行。
Still teaching myself python so please don't hate me if my code is terrible...
My code:
ifile = csv.reader(open("TE.csv",'rb'))
shutil.copy("TE.csv","temp")
tempfile = csv.reader(open("temp","rb"))
ofile = csv.writer(open("TE-RESULTS.csv","ab"))
for row in ifile:
#do some web scraping stuff here
VC_s = str(cells[1].find(text=True))
VC_i = str(cells[2].find(text=True))
VT_s = str(cells[4].find(text=True))
entry = [VC_s, VC_i, VT_s]
rowAdd = tempfile.next()
ofile.writerow(rowAdd + entry)
Problem: I start with a CSV that I will have to add 3 columns to the end. Using my code above, I get the following output:
HEADER1 HEADER2 HEADER3 result1 result2 result3
autocheck C:\check 1.jpg result1 result2 result3
services C:\svcs 2.jpg result1 result2 result3
My DESIRED output:
HEADER1 HEADER2 HEADER3 HEADER4 HEADER5 HEADER6
autocheck C:\check 1.jpg result1 result2 result3
services C:\svcs 2.jpg result1 result2 result3
What is the best way to fix my code that will give me the desired output? My initial thought would be to delete the HEADERS row and replace it with a new HEADERS row in the TE-RESULTS.csv file.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 for 循环之前处理标题行。
Process the header row before the for loop.